cleanup work
This commit is contained in:
@@ -5,12 +5,12 @@ import java.time.LocalTime;
|
|||||||
import java.time.Period;
|
import java.time.Period;
|
||||||
|
|
||||||
public class UseDuration {
|
public class UseDuration {
|
||||||
|
|
||||||
public LocalTime modifyDates(LocalTime localTime,Duration duration){
|
public LocalTime modifyDates(LocalTime localTime, Duration duration) {
|
||||||
return localTime.plus(duration);
|
return localTime.plus(duration);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Duration getDifferenceBetweenDates(LocalTime localTime1,LocalTime localTime2){
|
public Duration getDifferenceBetweenDates(LocalTime localTime1, LocalTime localTime2) {
|
||||||
return Duration.between(localTime1, localTime2);
|
return Duration.between(localTime1, localTime2);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,39 +7,39 @@ import java.time.temporal.ChronoUnit;
|
|||||||
import java.time.temporal.TemporalAdjusters;
|
import java.time.temporal.TemporalAdjusters;
|
||||||
|
|
||||||
public class UseLocalDate {
|
public class UseLocalDate {
|
||||||
|
|
||||||
public LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth){
|
public LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth) {
|
||||||
return LocalDate.of(year, month, dayOfMonth);
|
return LocalDate.of(year, month, dayOfMonth);
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDate getLocalDateUsingParseMethod(String representation){
|
public LocalDate getLocalDateUsingParseMethod(String representation) {
|
||||||
return LocalDate.parse(representation);
|
return LocalDate.parse(representation);
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDate getLocalDateFromClock(){
|
public LocalDate getLocalDateFromClock() {
|
||||||
LocalDate localDate = LocalDate.now();
|
LocalDate localDate = LocalDate.now();
|
||||||
return localDate;
|
return localDate;
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDate getNextDay(LocalDate localDate){
|
public LocalDate getNextDay(LocalDate localDate) {
|
||||||
return localDate.plusDays(1);
|
return localDate.plusDays(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDate getPreviousDay(LocalDate localDate){
|
public LocalDate getPreviousDay(LocalDate localDate) {
|
||||||
return localDate.minus(1, ChronoUnit.DAYS);
|
return localDate.minus(1, ChronoUnit.DAYS);
|
||||||
}
|
}
|
||||||
|
|
||||||
public DayOfWeek getDayOfWeek(LocalDate localDate){
|
public DayOfWeek getDayOfWeek(LocalDate localDate) {
|
||||||
DayOfWeek day = localDate.getDayOfWeek();
|
DayOfWeek day = localDate.getDayOfWeek();
|
||||||
return day;
|
return day;
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDate getFirstDayOfMonth(){
|
public LocalDate getFirstDayOfMonth() {
|
||||||
LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
|
LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
|
||||||
return firstDayOfMonth;
|
return firstDayOfMonth;
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDateTime getStartOfDay(LocalDate localDate){
|
public LocalDateTime getStartOfDay(LocalDate localDate) {
|
||||||
LocalDateTime startofDay = localDate.atStartOfDay();
|
LocalDateTime startofDay = localDate.atStartOfDay();
|
||||||
return startofDay;
|
return startofDay;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,8 +3,8 @@ package com.baeldung.datetime;
|
|||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
public class UseLocalDateTime {
|
public class UseLocalDateTime {
|
||||||
|
|
||||||
public LocalDateTime getLocalDateTimeUsingParseMethod(String representation){
|
public LocalDateTime getLocalDateTimeUsingParseMethod(String representation) {
|
||||||
return LocalDateTime.parse(representation);
|
return LocalDateTime.parse(representation);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,32 +4,32 @@ import java.time.LocalTime;
|
|||||||
import java.time.temporal.ChronoUnit;
|
import java.time.temporal.ChronoUnit;
|
||||||
|
|
||||||
public class UseLocalTime {
|
public class UseLocalTime {
|
||||||
|
|
||||||
public LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds){
|
public LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds) {
|
||||||
LocalTime localTime = LocalTime.of(hour, min, seconds);
|
LocalTime localTime = LocalTime.of(hour, min, seconds);
|
||||||
return localTime;
|
return localTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalTime getLocalTimeUsingParseMethod(String timeRepresentation){
|
public LocalTime getLocalTimeUsingParseMethod(String timeRepresentation) {
|
||||||
LocalTime localTime = LocalTime.parse(timeRepresentation);
|
LocalTime localTime = LocalTime.parse(timeRepresentation);
|
||||||
return localTime;
|
return localTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalTime getLocalTimeFromClock(){
|
public LocalTime getLocalTimeFromClock() {
|
||||||
LocalTime localTime = LocalTime.now();
|
LocalTime localTime = LocalTime.now();
|
||||||
return localTime;
|
return localTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalTime addAnHour(LocalTime localTime){
|
public LocalTime addAnHour(LocalTime localTime) {
|
||||||
LocalTime newTime = localTime.plus(1,ChronoUnit.HOURS);
|
LocalTime newTime = localTime.plus(1, ChronoUnit.HOURS);
|
||||||
return newTime;
|
return newTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getHourFromLocalTime(LocalTime localTime){
|
public int getHourFromLocalTime(LocalTime localTime) {
|
||||||
return localTime.getHour();
|
return localTime.getHour();
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute){
|
public LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute) {
|
||||||
return localTime.withMinute(minute);
|
return localTime.withMinute(minute);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,12 +4,12 @@ import java.time.LocalDate;
|
|||||||
import java.time.Period;
|
import java.time.Period;
|
||||||
|
|
||||||
public class UsePeriod {
|
public class UsePeriod {
|
||||||
|
|
||||||
public LocalDate modifyDates(LocalDate localDate,Period period){
|
public LocalDate modifyDates(LocalDate localDate, Period period) {
|
||||||
return localDate.plus(period);
|
return localDate.plus(period);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Period getDifferenceBetweenDates(LocalDate localDate1,LocalDate localDate2){
|
public Period getDifferenceBetweenDates(LocalDate localDate1, LocalDate localDate2) {
|
||||||
return Period.between(localDate1, localDate2);
|
return Period.between(localDate1, localDate2);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,13 +6,13 @@ import java.util.Calendar;
|
|||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
|
|
||||||
public class UseToInstant {
|
public class UseToInstant {
|
||||||
|
|
||||||
public LocalDateTime convertDateToLocalDate(Date date){
|
public LocalDateTime convertDateToLocalDate(Date date) {
|
||||||
LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
|
LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
|
||||||
return localDateTime;
|
return localDateTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDateTime convertDateToLocalDate(Calendar calendar){
|
public LocalDateTime convertDateToLocalDate(Calendar calendar) {
|
||||||
LocalDateTime localDateTime = LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault());
|
LocalDateTime localDateTime = LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault());
|
||||||
return localDateTime;
|
return localDateTime;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,8 +5,8 @@ import java.time.ZoneId;
|
|||||||
import java.time.ZonedDateTime;
|
import java.time.ZonedDateTime;
|
||||||
|
|
||||||
public class UseZonedDateTime {
|
public class UseZonedDateTime {
|
||||||
|
|
||||||
public ZonedDateTime getZonedDateTime(LocalDateTime localDateTime,ZoneId zoneId){
|
public ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) {
|
||||||
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
|
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
|
||||||
return zonedDateTime;
|
return zonedDateTime;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,8 +7,7 @@ import java.util.stream.Collectors;
|
|||||||
|
|
||||||
public class Pizza {
|
public class Pizza {
|
||||||
|
|
||||||
private static EnumSet<PizzaStatusEnum> deliveredPizzaStatuses =
|
private static EnumSet<PizzaStatusEnum> deliveredPizzaStatuses = EnumSet.of(PizzaStatusEnum.DELIVERED);
|
||||||
EnumSet.of(PizzaStatusEnum.DELIVERED);
|
|
||||||
|
|
||||||
private PizzaStatusEnum status;
|
private PizzaStatusEnum status;
|
||||||
|
|
||||||
@@ -76,9 +75,7 @@ public class Pizza {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static EnumMap<PizzaStatusEnum, List<Pizza>> groupPizzaByStatus(List<Pizza> pzList) {
|
public static EnumMap<PizzaStatusEnum, List<Pizza>> groupPizzaByStatus(List<Pizza> pzList) {
|
||||||
return pzList.stream().collect(
|
return pzList.stream().collect(Collectors.groupingBy(Pizza::getStatus, () -> new EnumMap<>(PizzaStatusEnum.class), Collectors.toList()));
|
||||||
Collectors.groupingBy(Pizza::getStatus,
|
|
||||||
() -> new EnumMap<>(PizzaStatusEnum.class), Collectors.toList()));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void deliver() {
|
public void deliver() {
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
package com.baeldung.enums;
|
package com.baeldung.enums;
|
||||||
|
|
||||||
|
|
||||||
public enum PizzaDeliverySystemConfiguration {
|
public enum PizzaDeliverySystemConfiguration {
|
||||||
INSTANCE;
|
INSTANCE;
|
||||||
|
|
||||||
|
|||||||
@@ -30,8 +30,7 @@ public class CustomRecursiveAction extends RecursiveAction {
|
|||||||
|
|
||||||
private Collection<CustomRecursiveAction> createSubtasks() {
|
private Collection<CustomRecursiveAction> createSubtasks() {
|
||||||
|
|
||||||
List<CustomRecursiveAction> subtasks =
|
List<CustomRecursiveAction> subtasks = new ArrayList<>();
|
||||||
new ArrayList<>();
|
|
||||||
|
|
||||||
String partOne = workLoad.substring(0, workLoad.length() / 2);
|
String partOne = workLoad.substring(0, workLoad.length() / 2);
|
||||||
String partTwo = workLoad.substring(workLoad.length() / 2, workLoad.length());
|
String partTwo = workLoad.substring(workLoad.length() / 2, workLoad.length());
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
package com.baeldung.forkjoin;
|
package com.baeldung.forkjoin;
|
||||||
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
@@ -23,10 +22,7 @@ public class CustomRecursiveTask extends RecursiveTask<Integer> {
|
|||||||
|
|
||||||
if (arr.length > THRESHOLD) {
|
if (arr.length > THRESHOLD) {
|
||||||
|
|
||||||
return ForkJoinTask.invokeAll(createSubtasks())
|
return ForkJoinTask.invokeAll(createSubtasks()).stream().mapToInt(ForkJoinTask::join).sum();
|
||||||
.stream()
|
|
||||||
.mapToInt(ForkJoinTask::join)
|
|
||||||
.sum();
|
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
return processing(arr);
|
return processing(arr);
|
||||||
@@ -35,17 +31,12 @@ public class CustomRecursiveTask extends RecursiveTask<Integer> {
|
|||||||
|
|
||||||
private Collection<CustomRecursiveTask> createSubtasks() {
|
private Collection<CustomRecursiveTask> createSubtasks() {
|
||||||
List<CustomRecursiveTask> dividedTasks = new ArrayList<>();
|
List<CustomRecursiveTask> dividedTasks = new ArrayList<>();
|
||||||
dividedTasks.add(new CustomRecursiveTask(
|
dividedTasks.add(new CustomRecursiveTask(Arrays.copyOfRange(arr, 0, arr.length / 2)));
|
||||||
Arrays.copyOfRange(arr, 0, arr.length / 2)));
|
dividedTasks.add(new CustomRecursiveTask(Arrays.copyOfRange(arr, arr.length / 2, arr.length)));
|
||||||
dividedTasks.add(new CustomRecursiveTask(
|
|
||||||
Arrays.copyOfRange(arr, arr.length / 2, arr.length)));
|
|
||||||
return dividedTasks;
|
return dividedTasks;
|
||||||
}
|
}
|
||||||
|
|
||||||
private Integer processing(int[] arr) {
|
private Integer processing(int[] arr) {
|
||||||
return Arrays.stream(arr)
|
return Arrays.stream(arr).filter(a -> a > 10 && a < 27).map(a -> a * 10).sum();
|
||||||
.filter(a -> a > 10 && a < 27)
|
|
||||||
.map(a -> a * 10)
|
|
||||||
.sum();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
package com.baeldung.forkjoin.util;
|
package com.baeldung.forkjoin.util;
|
||||||
|
|
||||||
|
|
||||||
import java.util.concurrent.ForkJoinPool;
|
import java.util.concurrent.ForkJoinPool;
|
||||||
|
|
||||||
public class PoolUtil {
|
public class PoolUtil {
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ public class EchoServer {
|
|||||||
|
|
||||||
public static void main(String[] args)
|
public static void main(String[] args)
|
||||||
|
|
||||||
throws IOException {
|
throws IOException {
|
||||||
Selector selector = Selector.open();
|
Selector selector = Selector.open();
|
||||||
ServerSocketChannel serverSocket = ServerSocketChannel.open();
|
ServerSocketChannel serverSocket = ServerSocketChannel.open();
|
||||||
serverSocket.bind(new InetSocketAddress("localhost", 5454));
|
serverSocket.bind(new InetSocketAddress("localhost", 5454));
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ public interface Vehicle {
|
|||||||
}
|
}
|
||||||
|
|
||||||
default long[] startPosition() {
|
default long[] startPosition() {
|
||||||
return new long[]{23, 15};
|
return new long[] { 23, 15 };
|
||||||
}
|
}
|
||||||
|
|
||||||
default String getOverview() {
|
default String getOverview() {
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
package com.baeldung.java_8_features;
|
package com.baeldung.java_8_features;
|
||||||
|
|
||||||
public class VehicleImpl implements Vehicle {
|
public class VehicleImpl implements Vehicle {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void moveTo(long altitude, long longitude) {
|
public void moveTo(long altitude, long longitude) {
|
||||||
//do nothing
|
// do nothing
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,39 +4,38 @@ import java.io.*;
|
|||||||
import java.net.*;
|
import java.net.*;
|
||||||
|
|
||||||
public class EchoClient {
|
public class EchoClient {
|
||||||
private Socket clientSocket;
|
private Socket clientSocket;
|
||||||
private PrintWriter out;
|
private PrintWriter out;
|
||||||
private BufferedReader in;
|
private BufferedReader in;
|
||||||
|
|
||||||
public void startConnection(String ip, int port) {
|
public void startConnection(String ip, int port) {
|
||||||
try {
|
try {
|
||||||
clientSocket = new Socket(ip, port);
|
clientSocket = new Socket(ip, port);
|
||||||
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
||||||
in = new BufferedReader(new InputStreamReader(
|
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
|
||||||
clientSocket.getInputStream()));
|
} catch (IOException e) {
|
||||||
} catch (IOException e) {
|
System.out.print(e);
|
||||||
System.out.print(e);
|
}
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public String sendMessage(String msg) {
|
public String sendMessage(String msg) {
|
||||||
try {
|
try {
|
||||||
out.println(msg);
|
out.println(msg);
|
||||||
return in.readLine();
|
return in.readLine();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void stopConnection() {
|
public void stopConnection() {
|
||||||
try {
|
try {
|
||||||
in.close();
|
in.close();
|
||||||
out.close();
|
out.close();
|
||||||
clientSocket.close();
|
clientSocket.close();
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,68 +4,67 @@ import java.net.*;
|
|||||||
import java.io.*;
|
import java.io.*;
|
||||||
|
|
||||||
public class EchoMultiServer {
|
public class EchoMultiServer {
|
||||||
private ServerSocket serverSocket;
|
private ServerSocket serverSocket;
|
||||||
|
|
||||||
public void start(int port) {
|
public void start(int port) {
|
||||||
try {
|
try {
|
||||||
serverSocket = new ServerSocket(port);
|
serverSocket = new ServerSocket(port);
|
||||||
while (true)
|
while (true)
|
||||||
new EchoClientHandler(serverSocket.accept()).run();
|
new EchoClientHandler(serverSocket.accept()).run();
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
} finally {
|
} finally {
|
||||||
stop();
|
stop();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void stop() {
|
public void stop() {
|
||||||
try {
|
try {
|
||||||
|
|
||||||
serverSocket.close();
|
serverSocket.close();
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static class EchoClientHandler extends Thread {
|
private static class EchoClientHandler extends Thread {
|
||||||
private Socket clientSocket;
|
private Socket clientSocket;
|
||||||
private PrintWriter out;
|
private PrintWriter out;
|
||||||
private BufferedReader in;
|
private BufferedReader in;
|
||||||
|
|
||||||
public EchoClientHandler(Socket socket) {
|
public EchoClientHandler(Socket socket) {
|
||||||
this.clientSocket = socket;
|
this.clientSocket = socket;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
||||||
in = new BufferedReader(new InputStreamReader(
|
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
|
||||||
clientSocket.getInputStream()));
|
String inputLine;
|
||||||
String inputLine;
|
while ((inputLine = in.readLine()) != null) {
|
||||||
while ((inputLine = in.readLine()) != null) {
|
if (".".equals(inputLine)) {
|
||||||
if (".".equals(inputLine)) {
|
out.println("bye");
|
||||||
out.println("bye");
|
break;
|
||||||
break;
|
}
|
||||||
}
|
out.println(inputLine);
|
||||||
out.println(inputLine);
|
}
|
||||||
}
|
|
||||||
|
|
||||||
in.close();
|
in.close();
|
||||||
out.close();
|
out.close();
|
||||||
clientSocket.close();
|
clientSocket.close();
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
EchoMultiServer server = new EchoMultiServer();
|
EchoMultiServer server = new EchoMultiServer();
|
||||||
server.start(5555);
|
server.start(5555);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,47 +4,46 @@ import java.net.*;
|
|||||||
import java.io.*;
|
import java.io.*;
|
||||||
|
|
||||||
public class EchoServer {
|
public class EchoServer {
|
||||||
private ServerSocket serverSocket;
|
private ServerSocket serverSocket;
|
||||||
private Socket clientSocket;
|
private Socket clientSocket;
|
||||||
private PrintWriter out;
|
private PrintWriter out;
|
||||||
private BufferedReader in;
|
private BufferedReader in;
|
||||||
|
|
||||||
public void start(int port) {
|
public void start(int port) {
|
||||||
try {
|
try {
|
||||||
serverSocket = new ServerSocket(port);
|
serverSocket = new ServerSocket(port);
|
||||||
clientSocket = serverSocket.accept();
|
clientSocket = serverSocket.accept();
|
||||||
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
||||||
in = new BufferedReader(new InputStreamReader(
|
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
|
||||||
clientSocket.getInputStream()));
|
String inputLine;
|
||||||
String inputLine;
|
while ((inputLine = in.readLine()) != null) {
|
||||||
while ((inputLine = in.readLine()) != null) {
|
if (".".equals(inputLine)) {
|
||||||
if (".".equals(inputLine)) {
|
out.println("good bye");
|
||||||
out.println("good bye");
|
break;
|
||||||
break;
|
}
|
||||||
}
|
out.println(inputLine);
|
||||||
out.println(inputLine);
|
}
|
||||||
}
|
} catch (IOException e) {
|
||||||
} catch (IOException e) {
|
e.printStackTrace();
|
||||||
e.printStackTrace();
|
}
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void stop() {
|
public void stop() {
|
||||||
try {
|
try {
|
||||||
in.close();
|
in.close();
|
||||||
out.close();
|
out.close();
|
||||||
clientSocket.close();
|
clientSocket.close();
|
||||||
serverSocket.close();
|
serverSocket.close();
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
EchoServer server = new EchoServer();
|
EchoServer server = new EchoServer();
|
||||||
server.start(4444);
|
server.start(4444);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,39 +7,38 @@ import java.io.PrintWriter;
|
|||||||
import java.net.Socket;
|
import java.net.Socket;
|
||||||
|
|
||||||
public class GreetClient {
|
public class GreetClient {
|
||||||
private Socket clientSocket;
|
private Socket clientSocket;
|
||||||
private PrintWriter out;
|
private PrintWriter out;
|
||||||
private BufferedReader in;
|
private BufferedReader in;
|
||||||
|
|
||||||
public void startConnection(String ip, int port) {
|
public void startConnection(String ip, int port) {
|
||||||
try {
|
try {
|
||||||
clientSocket = new Socket(ip, port);
|
clientSocket = new Socket(ip, port);
|
||||||
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
||||||
in = new BufferedReader(new InputStreamReader(
|
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
|
||||||
clientSocket.getInputStream()));
|
} catch (IOException e) {
|
||||||
} catch (IOException e) {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public String sendMessage(String msg) {
|
}
|
||||||
try {
|
|
||||||
out.println(msg);
|
|
||||||
return in.readLine();
|
|
||||||
} catch (Exception e) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void stopConnection() {
|
public String sendMessage(String msg) {
|
||||||
try {
|
try {
|
||||||
in.close();
|
out.println(msg);
|
||||||
out.close();
|
return in.readLine();
|
||||||
clientSocket.close();
|
} catch (Exception e) {
|
||||||
} catch (IOException e) {
|
return null;
|
||||||
e.printStackTrace();
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
public void stopConnection() {
|
||||||
|
try {
|
||||||
|
in.close();
|
||||||
|
out.close();
|
||||||
|
clientSocket.close();
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,44 +4,43 @@ import java.net.*;
|
|||||||
import java.io.*;
|
import java.io.*;
|
||||||
|
|
||||||
public class GreetServer {
|
public class GreetServer {
|
||||||
private ServerSocket serverSocket;
|
private ServerSocket serverSocket;
|
||||||
private Socket clientSocket;
|
private Socket clientSocket;
|
||||||
private PrintWriter out;
|
private PrintWriter out;
|
||||||
private BufferedReader in;
|
private BufferedReader in;
|
||||||
|
|
||||||
|
public void start(int port) {
|
||||||
|
try {
|
||||||
|
serverSocket = new ServerSocket(port);
|
||||||
|
clientSocket = serverSocket.accept();
|
||||||
|
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
||||||
|
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
|
||||||
|
String greeting = in.readLine();
|
||||||
|
if ("hello server".equals(greeting))
|
||||||
|
out.println("hello client");
|
||||||
|
else
|
||||||
|
out.println("unrecognised greeting");
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
public void start(int port) {
|
}
|
||||||
try {
|
|
||||||
serverSocket = new ServerSocket(port);
|
|
||||||
clientSocket = serverSocket.accept();
|
|
||||||
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
|
||||||
in = new BufferedReader(new InputStreamReader(
|
|
||||||
clientSocket.getInputStream()));
|
|
||||||
String greeting = in.readLine();
|
|
||||||
if ("hello server".equals(greeting))
|
|
||||||
out.println("hello client");
|
|
||||||
else
|
|
||||||
out.println("unrecognised greeting");
|
|
||||||
} catch (IOException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
public void stop() {
|
||||||
|
try {
|
||||||
|
in.close();
|
||||||
|
out.close();
|
||||||
|
clientSocket.close();
|
||||||
|
serverSocket.close();
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
public void stop() {
|
}
|
||||||
try {
|
|
||||||
in.close();
|
|
||||||
out.close();
|
|
||||||
clientSocket.close();
|
|
||||||
serverSocket.close();
|
|
||||||
} catch (IOException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
public static void main(String[] args) {
|
||||||
public static void main(String[] args) {
|
GreetServer server = new GreetServer();
|
||||||
GreetServer server=new GreetServer();
|
server.start(6666);
|
||||||
server.start(6666);
|
}
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -44,7 +44,6 @@ public class Product {
|
|||||||
this.name = name;
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public static Stream<String> streamOf(List<String> list) {
|
public static Stream<String> streamOf(List<String> list) {
|
||||||
return (list == null || list.isEmpty()) ? Stream.empty() : list.stream();
|
return (list == null || list.isEmpty()) ? Stream.empty() : list.stream();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,9 +14,7 @@ public class CountingTask extends RecursiveTask<Integer> {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected Integer compute() {
|
protected Integer compute() {
|
||||||
return node.value + node.children.stream()
|
return node.value + node.children.stream().map(childNode -> new CountingTask(childNode).fork()).collect(Collectors.summingInt(ForkJoinTask::join));
|
||||||
.map(childNode -> new CountingTask(childNode).fork())
|
|
||||||
.collect(Collectors.summingInt(ForkJoinTask::join));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,8 +4,8 @@ import javax.swing.JOptionPane;
|
|||||||
|
|
||||||
public class ExecutableMavenJar {
|
public class ExecutableMavenJar {
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
JOptionPane.showMessageDialog(null, "It worked!", "Executable Jar with Maven", 1);
|
JOptionPane.showMessageDialog(null, "It worked!", "Executable Jar with Maven", 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
|||||||
public class CharToStringTest {
|
public class CharToStringTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenChar_whenCallingStringValueOf_shouldConvertToString(){
|
public void givenChar_whenCallingStringValueOf_shouldConvertToString() {
|
||||||
final char givenChar = 'x';
|
final char givenChar = 'x';
|
||||||
|
|
||||||
final String result = String.valueOf(givenChar);
|
final String result = String.valueOf(givenChar);
|
||||||
@@ -16,7 +16,7 @@ public class CharToStringTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenChar_whenCallingToStringOnCharacter_shouldConvertToString(){
|
public void givenChar_whenCallingToStringOnCharacter_shouldConvertToString() {
|
||||||
final char givenChar = 'x';
|
final char givenChar = 'x';
|
||||||
|
|
||||||
final String result = Character.toString(givenChar);
|
final String result = Character.toString(givenChar);
|
||||||
@@ -25,7 +25,7 @@ public class CharToStringTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenChar_whenCallingCharacterConstructor_shouldConvertToString3(){
|
public void givenChar_whenCallingCharacterConstructor_shouldConvertToString3() {
|
||||||
final char givenChar = 'x';
|
final char givenChar = 'x';
|
||||||
|
|
||||||
final String result = new Character(givenChar).toString();
|
final String result = new Character(givenChar).toString();
|
||||||
@@ -34,7 +34,7 @@ public class CharToStringTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenChar_whenConcatenated_shouldConvertToString4(){
|
public void givenChar_whenConcatenated_shouldConvertToString4() {
|
||||||
final char givenChar = 'x';
|
final char givenChar = 'x';
|
||||||
|
|
||||||
final String result = givenChar + "";
|
final String result = givenChar + "";
|
||||||
@@ -43,7 +43,7 @@ public class CharToStringTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenChar_whenFormated_shouldConvertToString5(){
|
public void givenChar_whenFormated_shouldConvertToString5() {
|
||||||
final char givenChar = 'x';
|
final char givenChar = 'x';
|
||||||
|
|
||||||
final String result = String.format("%c", givenChar);
|
final String result = String.format("%c", givenChar);
|
||||||
|
|||||||
+2
-2
@@ -6,7 +6,7 @@ import org.junit.Test;
|
|||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.util.concurrent.ThreadLocalRandom;
|
import java.util.concurrent.ThreadLocalRandom;
|
||||||
|
|
||||||
public class RandomListElementTest {
|
public class RandomListElementUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingRandom() {
|
public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingRandom() {
|
||||||
@@ -20,7 +20,7 @@ public class RandomListElementTest {
|
|||||||
public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingMathRandom() {
|
public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingMathRandom() {
|
||||||
List<Integer> givenList = Lists.newArrayList(1, 2, 3);
|
List<Integer> givenList = Lists.newArrayList(1, 2, 3);
|
||||||
|
|
||||||
givenList.get((int)(Math.random() * givenList.size()));
|
givenList.get((int) (Math.random() * givenList.size()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
+5
-5
@@ -1,11 +1,12 @@
|
|||||||
package com.baeldung;
|
package com.baeldung;
|
||||||
|
|
||||||
import com.google.common.primitives.Ints;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
public class StringToIntOrIntegerTest {
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.google.common.primitives.Ints;
|
||||||
|
|
||||||
|
public class StringToIntOrIntegerUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenString_whenParsingInt_shouldConvertToInt() {
|
public void givenString_whenParsingInt_shouldConvertToInt() {
|
||||||
@@ -16,7 +17,6 @@ public class StringToIntOrIntegerTest {
|
|||||||
assertThat(result).isEqualTo(42);
|
assertThat(result).isEqualTo(42);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenString_whenCallingIntegerValueOf_shouldConvertToInt() {
|
public void givenString_whenCallingIntegerValueOf_shouldConvertToInt() {
|
||||||
String givenString = "42";
|
String givenString = "42";
|
||||||
@@ -42,192 +42,137 @@ public class Java8CollectorsTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToList_shouldCollectToList() throws Exception {
|
public void whenCollectingToList_shouldCollectToList() throws Exception {
|
||||||
final List<String> result = givenList.stream()
|
final List<String> result = givenList.stream().collect(toList());
|
||||||
.collect(toList());
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsAll(givenList);
|
||||||
.containsAll(givenList);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToList_shouldCollectToSet() throws Exception {
|
public void whenCollectingToList_shouldCollectToSet() throws Exception {
|
||||||
final Set<String> result = givenList.stream()
|
final Set<String> result = givenList.stream().collect(toSet());
|
||||||
.collect(toSet());
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsAll(givenList);
|
||||||
.containsAll(givenList);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToCollection_shouldCollectToCollection() throws Exception {
|
public void whenCollectingToCollection_shouldCollectToCollection() throws Exception {
|
||||||
final List<String> result = givenList.stream()
|
final List<String> result = givenList.stream().collect(toCollection(LinkedList::new));
|
||||||
.collect(toCollection(LinkedList::new));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsAll(givenList).isInstanceOf(LinkedList.class);
|
||||||
.containsAll(givenList)
|
|
||||||
.isInstanceOf(LinkedList.class);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception {
|
public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception {
|
||||||
assertThatThrownBy(() -> {
|
assertThatThrownBy(() -> {
|
||||||
givenList.stream()
|
givenList.stream().collect(toCollection(ImmutableList::of));
|
||||||
.collect(toCollection(ImmutableList::of));
|
|
||||||
}).isInstanceOf(UnsupportedOperationException.class);
|
}).isInstanceOf(UnsupportedOperationException.class);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToMap_shouldCollectToMap() throws Exception {
|
public void whenCollectingToMap_shouldCollectToMap() throws Exception {
|
||||||
final Map<String, Integer> result = givenList.stream()
|
final Map<String, Integer> result = givenList.stream().collect(toMap(Function.identity(), String::length));
|
||||||
.collect(toMap(Function.identity(), String::length));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
|
||||||
.containsEntry("a", 1)
|
|
||||||
.containsEntry("bb", 2)
|
|
||||||
.containsEntry("ccc", 3)
|
|
||||||
.containsEntry("dd", 2);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToMap_shouldCollectToMapMerging() throws Exception {
|
public void whenCollectingToMap_shouldCollectToMapMerging() throws Exception {
|
||||||
final Map<String, Integer> result = givenList.stream()
|
final Map<String, Integer> result = givenList.stream().collect(toMap(Function.identity(), String::length, (i1, i2) -> i1));
|
||||||
.collect(toMap(Function.identity(), String::length, (i1, i2) -> i1));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
|
||||||
.containsEntry("a", 1)
|
|
||||||
.containsEntry("bb", 2)
|
|
||||||
.containsEntry("ccc", 3)
|
|
||||||
.containsEntry("dd", 2);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingAndThen_shouldCollect() throws Exception {
|
public void whenCollectingAndThen_shouldCollect() throws Exception {
|
||||||
final List<String> result = givenList.stream()
|
final List<String> result = givenList.stream().collect(collectingAndThen(toList(), ImmutableList::copyOf));
|
||||||
.collect(collectingAndThen(toList(), ImmutableList::copyOf));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsAll(givenList).isInstanceOf(ImmutableList.class);
|
||||||
.containsAll(givenList)
|
|
||||||
.isInstanceOf(ImmutableList.class);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenJoining_shouldJoin() throws Exception {
|
public void whenJoining_shouldJoin() throws Exception {
|
||||||
final String result = givenList.stream()
|
final String result = givenList.stream().collect(joining());
|
||||||
.collect(joining());
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).isEqualTo("abbcccdd");
|
||||||
.isEqualTo("abbcccdd");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception {
|
public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception {
|
||||||
final String result = givenList.stream()
|
final String result = givenList.stream().collect(joining(" "));
|
||||||
.collect(joining(" "));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).isEqualTo("a bb ccc dd");
|
||||||
.isEqualTo("a bb ccc dd");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception {
|
public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception {
|
||||||
final String result = givenList.stream()
|
final String result = givenList.stream().collect(joining(" ", "PRE-", "-POST"));
|
||||||
.collect(joining(" ", "PRE-", "-POST"));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).isEqualTo("PRE-a bb ccc dd-POST");
|
||||||
.isEqualTo("PRE-a bb ccc dd-POST");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenPartitioningBy_shouldPartition() throws Exception {
|
public void whenPartitioningBy_shouldPartition() throws Exception {
|
||||||
final Map<Boolean, List<String>> result = givenList.stream()
|
final Map<Boolean, List<String>> result = givenList.stream().collect(partitioningBy(s -> s.length() > 2));
|
||||||
.collect(partitioningBy(s -> s.length() > 2));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsKeys(true, false).satisfies(booleanListMap -> {
|
||||||
.containsKeys(true, false)
|
assertThat(booleanListMap.get(true)).contains("ccc");
|
||||||
.satisfies(booleanListMap -> {
|
|
||||||
assertThat(booleanListMap.get(true))
|
|
||||||
.contains("ccc");
|
|
||||||
|
|
||||||
assertThat(booleanListMap.get(false))
|
assertThat(booleanListMap.get(false)).contains("a", "bb", "dd");
|
||||||
.contains("a", "bb", "dd");
|
});
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCounting_shouldCount() throws Exception {
|
public void whenCounting_shouldCount() throws Exception {
|
||||||
final Long result = givenList.stream()
|
final Long result = givenList.stream().collect(counting());
|
||||||
.collect(counting());
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).isEqualTo(4);
|
||||||
.isEqualTo(4);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenSummarizing_shouldSummarize() throws Exception {
|
public void whenSummarizing_shouldSummarize() throws Exception {
|
||||||
final DoubleSummaryStatistics result = givenList.stream()
|
final DoubleSummaryStatistics result = givenList.stream().collect(summarizingDouble(String::length));
|
||||||
.collect(summarizingDouble(String::length));
|
|
||||||
|
|
||||||
assertThat(result.getAverage())
|
assertThat(result.getAverage()).isEqualTo(2);
|
||||||
.isEqualTo(2);
|
assertThat(result.getCount()).isEqualTo(4);
|
||||||
assertThat(result.getCount())
|
assertThat(result.getMax()).isEqualTo(3);
|
||||||
.isEqualTo(4);
|
assertThat(result.getMin()).isEqualTo(1);
|
||||||
assertThat(result.getMax())
|
assertThat(result.getSum()).isEqualTo(8);
|
||||||
.isEqualTo(3);
|
|
||||||
assertThat(result.getMin())
|
|
||||||
.isEqualTo(1);
|
|
||||||
assertThat(result.getSum())
|
|
||||||
.isEqualTo(8);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenAveraging_shouldAverage() throws Exception {
|
public void whenAveraging_shouldAverage() throws Exception {
|
||||||
final Double result = givenList.stream()
|
final Double result = givenList.stream().collect(averagingDouble(String::length));
|
||||||
.collect(averagingDouble(String::length));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).isEqualTo(2);
|
||||||
.isEqualTo(2);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenSumming_shouldSum() throws Exception {
|
public void whenSumming_shouldSum() throws Exception {
|
||||||
final Double result = givenList.stream()
|
final Double result = givenList.stream().collect(summingDouble(String::length));
|
||||||
.collect(summingDouble(String::length));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).isEqualTo(8);
|
||||||
.isEqualTo(8);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenMaxingBy_shouldMaxBy() throws Exception {
|
public void whenMaxingBy_shouldMaxBy() throws Exception {
|
||||||
final Optional<String> result = givenList.stream()
|
final Optional<String> result = givenList.stream().collect(maxBy(Comparator.naturalOrder()));
|
||||||
.collect(maxBy(Comparator.naturalOrder()));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).isPresent().hasValue("dd");
|
||||||
.isPresent()
|
|
||||||
.hasValue("dd");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenGroupingBy_shouldGroupBy() throws Exception {
|
public void whenGroupingBy_shouldGroupBy() throws Exception {
|
||||||
final Map<Integer, Set<String>> result = givenList.stream()
|
final Map<Integer, Set<String>> result = givenList.stream().collect(groupingBy(String::length, toSet()));
|
||||||
.collect(groupingBy(String::length, toSet()));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsEntry(1, newHashSet("a")).containsEntry(2, newHashSet("bb", "dd")).containsEntry(3, newHashSet("ccc"));
|
||||||
.containsEntry(1, newHashSet("a"))
|
|
||||||
.containsEntry(2, newHashSet("bb", "dd"))
|
|
||||||
.containsEntry(3, newHashSet("ccc"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCreatingCustomCollector_shouldCollect() throws Exception {
|
public void whenCreatingCustomCollector_shouldCollect() throws Exception {
|
||||||
final ImmutableSet<String> result = givenList.stream()
|
final ImmutableSet<String> result = givenList.stream().collect(toImmutableSet());
|
||||||
.collect(toImmutableSet());
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).isInstanceOf(ImmutableSet.class).contains("a", "bb", "ccc", "dd");
|
||||||
.isInstanceOf(ImmutableSet.class)
|
|
||||||
.contains("a", "bb", "ccc", "dd");
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -43,7 +43,6 @@ public class CompletableFutureTest {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public Future<String> calculateAsyncWithCancellation() throws InterruptedException {
|
public Future<String> calculateAsyncWithCancellation() throws InterruptedException {
|
||||||
CompletableFuture<String> completableFuture = new CompletableFuture<>();
|
CompletableFuture<String> completableFuture = new CompletableFuture<>();
|
||||||
|
|
||||||
@@ -56,7 +55,6 @@ public class CompletableFutureTest {
|
|||||||
return completableFuture;
|
return completableFuture;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test(expected = CancellationException.class)
|
@Test(expected = CancellationException.class)
|
||||||
public void whenCancelingTheFuture_thenThrowsCancellationException() throws ExecutionException, InterruptedException {
|
public void whenCancelingTheFuture_thenThrowsCancellationException() throws ExecutionException, InterruptedException {
|
||||||
|
|
||||||
@@ -110,8 +108,7 @@ public class CompletableFutureTest {
|
|||||||
@Test
|
@Test
|
||||||
public void whenUsingThenCompose_thenFuturesExecuteSequentially() throws ExecutionException, InterruptedException {
|
public void whenUsingThenCompose_thenFuturesExecuteSequentially() throws ExecutionException, InterruptedException {
|
||||||
|
|
||||||
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello")
|
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World"));
|
||||||
.thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World"));
|
|
||||||
|
|
||||||
assertEquals("Hello World", completableFuture.get());
|
assertEquals("Hello World", completableFuture.get());
|
||||||
|
|
||||||
@@ -120,9 +117,7 @@ public class CompletableFutureTest {
|
|||||||
@Test
|
@Test
|
||||||
public void whenUsingThenCombine_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException {
|
public void whenUsingThenCombine_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException {
|
||||||
|
|
||||||
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello")
|
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenCombine(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> s1 + s2);
|
||||||
.thenCombine(CompletableFuture.supplyAsync(() -> " World"),
|
|
||||||
(s1, s2) -> s1 + s2);
|
|
||||||
|
|
||||||
assertEquals("Hello World", completableFuture.get());
|
assertEquals("Hello World", completableFuture.get());
|
||||||
|
|
||||||
@@ -131,9 +126,7 @@ public class CompletableFutureTest {
|
|||||||
@Test
|
@Test
|
||||||
public void whenUsingThenAcceptBoth_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException {
|
public void whenUsingThenAcceptBoth_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException {
|
||||||
|
|
||||||
CompletableFuture.supplyAsync(() -> "Hello")
|
CompletableFuture.supplyAsync(() -> "Hello").thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> System.out.println(s1 + s2));
|
||||||
.thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"),
|
|
||||||
(s1, s2) -> System.out.println(s1 + s2));
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -154,9 +147,7 @@ public class CompletableFutureTest {
|
|||||||
assertTrue(future2.isDone());
|
assertTrue(future2.isDone());
|
||||||
assertTrue(future3.isDone());
|
assertTrue(future3.isDone());
|
||||||
|
|
||||||
String combined = Stream.of(future1, future2, future3)
|
String combined = Stream.of(future1, future2, future3).map(CompletableFuture::join).collect(Collectors.joining(" "));
|
||||||
.map(CompletableFuture::join)
|
|
||||||
.collect(Collectors.joining(" "));
|
|
||||||
|
|
||||||
assertEquals("Hello Beautiful World", combined);
|
assertEquals("Hello Beautiful World", combined);
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -14,7 +14,7 @@ import java.time.temporal.ChronoUnit;
|
|||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
public class JavaUtilTimeTest {
|
public class JavaUtilTimeUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void currentTime() {
|
public void currentTime() {
|
||||||
+27
-44
@@ -1,7 +1,8 @@
|
|||||||
package com.baeldung.functionalinterface;
|
package com.baeldung.functionalinterface;
|
||||||
|
|
||||||
import com.google.common.util.concurrent.Uninterruptibles;
|
import static org.junit.Assert.assertArrayEquals;
|
||||||
import org.junit.Test;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
@@ -13,54 +14,43 @@ import java.util.function.Supplier;
|
|||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class FunctionalInterfaceTest {
|
import com.google.common.util.concurrent.Uninterruptibles;
|
||||||
|
|
||||||
|
public class FunctionalInterfaceUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() {
|
public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() {
|
||||||
|
|
||||||
Map<String, Integer> nameMap = new HashMap<>();
|
Map<String, Integer> nameMap = new HashMap<>();
|
||||||
Integer value = nameMap.computeIfAbsent("John", s -> s.length());
|
Integer value = nameMap.computeIfAbsent("John", s -> s.length());
|
||||||
|
|
||||||
assertEquals(new Integer(4), nameMap.get("John"));
|
assertEquals(new Integer(4), nameMap.get("John"));
|
||||||
assertEquals(new Integer(4), value);
|
assertEquals(new Integer(4), value);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenPassingMethodReferenceToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() {
|
public void whenPassingMethodReferenceToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() {
|
||||||
|
|
||||||
Map<String, Integer> nameMap = new HashMap<>();
|
Map<String, Integer> nameMap = new HashMap<>();
|
||||||
Integer value = nameMap.computeIfAbsent("John", String::length);
|
Integer value = nameMap.computeIfAbsent("John", String::length);
|
||||||
|
|
||||||
assertEquals(new Integer(4), nameMap.get("John"));
|
assertEquals(new Integer(4), nameMap.get("John"));
|
||||||
assertEquals(new Integer(4), value);
|
assertEquals(new Integer(4), value);
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
public byte[] transformArray(short[] array, ShortToByteFunction function) {
|
|
||||||
byte[] transformedArray = new byte[array.length];
|
|
||||||
for (int i = 0; i < array.length; i++) {
|
|
||||||
transformedArray[i] = function.applyAsByte(array[i]);
|
|
||||||
}
|
|
||||||
return transformedArray;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingCustomFunctionalInterfaceForPrimitives_thenCanUseItAsLambda() {
|
public void whenUsingCustomFunctionalInterfaceForPrimitives_thenCanUseItAsLambda() {
|
||||||
|
|
||||||
short[] array = {(short) 1, (short) 2, (short) 3};
|
short[] array = { (short) 1, (short) 2, (short) 3 };
|
||||||
byte[] transformedArray = transformArray(array, s -> (byte) (s * 2));
|
byte[] transformedArray = transformArray(array, s -> (byte) (s * 2));
|
||||||
|
|
||||||
byte[] expectedArray = {(byte) 2, (byte) 4, (byte) 6};
|
byte[] expectedArray = { (byte) 2, (byte) 4, (byte) 6 };
|
||||||
assertArrayEquals(expectedArray, transformedArray);
|
assertArrayEquals(expectedArray, transformedArray);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingBiFunction_thenCanUseItToReplaceMapValues() {
|
public void whenUsingBiFunction_thenCanUseItToReplaceMapValues() {
|
||||||
|
|
||||||
Map<String, Integer> salaries = new HashMap<>();
|
Map<String, Integer> salaries = new HashMap<>();
|
||||||
salaries.put("John", 40000);
|
salaries.put("John", 40000);
|
||||||
salaries.put("Freddy", 30000);
|
salaries.put("Freddy", 30000);
|
||||||
@@ -71,22 +61,18 @@ public class FunctionalInterfaceTest {
|
|||||||
assertEquals(new Integer(50000), salaries.get("John"));
|
assertEquals(new Integer(50000), salaries.get("John"));
|
||||||
assertEquals(new Integer(30000), salaries.get("Freddy"));
|
assertEquals(new Integer(30000), salaries.get("Freddy"));
|
||||||
assertEquals(new Integer(60000), salaries.get("Samuel"));
|
assertEquals(new Integer(60000), salaries.get("Samuel"));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenPassingLambdaToThreadConstructor_thenLambdaInferredToRunnable() {
|
public void whenPassingLambdaToThreadConstructor_thenLambdaInferredToRunnable() {
|
||||||
|
|
||||||
Thread thread = new Thread(() -> System.out.println("Hello From Another Thread"));
|
Thread thread = new Thread(() -> System.out.println("Hello From Another Thread"));
|
||||||
thread.start();
|
thread.start();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingSupplierToGenerateNumbers_thenCanUseItInStreamGenerate() {
|
public void whenUsingSupplierToGenerateNumbers_thenCanUseItInStreamGenerate() {
|
||||||
|
|
||||||
int[] fibs = {0, 1};
|
int[] fibs = { 0, 1 };
|
||||||
Stream<Integer> fibonacci = Stream.generate(() -> {
|
Stream<Integer> fibonacci = Stream.generate(() -> {
|
||||||
int result = fibs[1];
|
int result = fibs[1];
|
||||||
int fib3 = fibs[0] + fibs[1];
|
int fib3 = fibs[0] + fibs[1];
|
||||||
@@ -95,55 +81,44 @@ public class FunctionalInterfaceTest {
|
|||||||
return result;
|
return result;
|
||||||
});
|
});
|
||||||
|
|
||||||
List<Integer> fibonacci5 = fibonacci.limit(5)
|
List<Integer> fibonacci5 = fibonacci.limit(5).collect(Collectors.toList());
|
||||||
.collect(Collectors.toList());
|
|
||||||
|
|
||||||
assertEquals(new Integer(1), fibonacci5.get(0));
|
assertEquals(new Integer(1), fibonacci5.get(0));
|
||||||
assertEquals(new Integer(1), fibonacci5.get(1));
|
assertEquals(new Integer(1), fibonacci5.get(1));
|
||||||
assertEquals(new Integer(2), fibonacci5.get(2));
|
assertEquals(new Integer(2), fibonacci5.get(2));
|
||||||
assertEquals(new Integer(3), fibonacci5.get(3));
|
assertEquals(new Integer(3), fibonacci5.get(3));
|
||||||
assertEquals(new Integer(5), fibonacci5.get(4));
|
assertEquals(new Integer(5), fibonacci5.get(4));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingConsumerInForEach_thenConsumerExecutesForEachListElement() {
|
public void whenUsingConsumerInForEach_thenConsumerExecutesForEachListElement() {
|
||||||
|
|
||||||
List<String> names = Arrays.asList("John", "Freddy", "Samuel");
|
List<String> names = Arrays.asList("John", "Freddy", "Samuel");
|
||||||
names.forEach(name -> System.out.println("Hello, " + name));
|
names.forEach(name -> System.out.println("Hello, " + name));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingBiConsumerInForEach_thenConsumerExecutesForEachMapElement() {
|
public void whenUsingBiConsumerInForEach_thenConsumerExecutesForEachMapElement() {
|
||||||
|
|
||||||
Map<String, Integer> ages = new HashMap<>();
|
Map<String, Integer> ages = new HashMap<>();
|
||||||
ages.put("John", 25);
|
ages.put("John", 25);
|
||||||
ages.put("Freddy", 24);
|
ages.put("Freddy", 24);
|
||||||
ages.put("Samuel", 30);
|
ages.put("Samuel", 30);
|
||||||
|
|
||||||
ages.forEach((name, age) -> System.out.println(name + " is " + age + " years old"));
|
ages.forEach((name, age) -> System.out.println(name + " is " + age + " years old"));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingPredicateInFilter_thenListValuesAreFilteredOut() {
|
public void whenUsingPredicateInFilter_thenListValuesAreFilteredOut() {
|
||||||
|
|
||||||
List<String> names = Arrays.asList("Angela", "Aaron", "Bob", "Claire", "David");
|
List<String> names = Arrays.asList("Angela", "Aaron", "Bob", "Claire", "David");
|
||||||
|
|
||||||
List<String> namesWithA = names.stream()
|
List<String> namesWithA = names.stream().filter(name -> name.startsWith("A")).collect(Collectors.toList());
|
||||||
.filter(name -> name.startsWith("A"))
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
|
|
||||||
assertEquals(2, namesWithA.size());
|
assertEquals(2, namesWithA.size());
|
||||||
assertTrue(namesWithA.contains("Angela"));
|
assertTrue(namesWithA.contains("Angela"));
|
||||||
assertTrue(namesWithA.contains("Aaron"));
|
assertTrue(namesWithA.contains("Aaron"));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingUnaryOperatorWithReplaceAll_thenAllValuesInTheListAreReplaced() {
|
public void whenUsingUnaryOperatorWithReplaceAll_thenAllValuesInTheListAreReplaced() {
|
||||||
|
|
||||||
List<String> names = Arrays.asList("bob", "josh", "megan");
|
List<String> names = Arrays.asList("bob", "josh", "megan");
|
||||||
|
|
||||||
names.replaceAll(String::toUpperCase);
|
names.replaceAll(String::toUpperCase);
|
||||||
@@ -151,7 +126,6 @@ public class FunctionalInterfaceTest {
|
|||||||
assertEquals("BOB", names.get(0));
|
assertEquals("BOB", names.get(0));
|
||||||
assertEquals("JOSH", names.get(1));
|
assertEquals("JOSH", names.get(1));
|
||||||
assertEquals("MEGAN", names.get(2));
|
assertEquals("MEGAN", names.get(2));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -159,8 +133,7 @@ public class FunctionalInterfaceTest {
|
|||||||
|
|
||||||
List<Integer> values = Arrays.asList(3, 5, 8, 9, 12);
|
List<Integer> values = Arrays.asList(3, 5, 8, 9, 12);
|
||||||
|
|
||||||
int sum = values.stream()
|
int sum = values.stream().reduce(0, (i1, i2) -> i1 + i2);
|
||||||
.reduce(0, (i1, i2) -> i1 + i2);
|
|
||||||
|
|
||||||
assertEquals(37, sum);
|
assertEquals(37, sum);
|
||||||
|
|
||||||
@@ -178,10 +151,6 @@ public class FunctionalInterfaceTest {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public double squareLazy(Supplier<Double> lazyValue) {
|
|
||||||
return Math.pow(lazyValue.get(), 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingSupplierToGenerateValue_thenValueIsGeneratedLazily() {
|
public void whenUsingSupplierToGenerateValue_thenValueIsGeneratedLazily() {
|
||||||
|
|
||||||
@@ -196,4 +165,18 @@ public class FunctionalInterfaceTest {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
|
||||||
|
public double squareLazy(Supplier<Double> lazyValue) {
|
||||||
|
return Math.pow(lazyValue.get(), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] transformArray(short[] array, ShortToByteFunction function) {
|
||||||
|
byte[] transformedArray = new byte[array.length];
|
||||||
|
for (int i = 0; i < array.length; i++) {
|
||||||
|
transformedArray[i] = function.applyAsByte(array[i]);
|
||||||
|
}
|
||||||
|
return transformedArray;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user