move java8 code (#2535)
* fix spring config * fix spring config * fix spring config * minor fix * fix spring-boot module * fix pom * upgrade jackson * minor fix * java concurrency * cleanup * fix conflict * java 8 * clean up * add core-java-8 to main pom
This commit is contained in:
committed by
Grzegorz Piwowarek
parent
2aeef70d39
commit
9c03b45c23
@@ -22,19 +22,11 @@
|
||||
- [Guide to the Java ArrayList](http://www.baeldung.com/java-arraylist)
|
||||
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
|
||||
- [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets)
|
||||
- [Java 8 Collectors](http://www.baeldung.com/java-8-collectors)
|
||||
- [Guide to Java 8’s Functional Interfaces](http://www.baeldung.com/java-8-functional-interfaces)
|
||||
- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string)
|
||||
- [Random List Element](http://www.baeldung.com/java-random-list-element)
|
||||
- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer)
|
||||
- [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda)
|
||||
- [Java – Directory Size](http://www.baeldung.com/java-folder-size)
|
||||
- [Java – Try with Resources](http://www.baeldung.com/java-try-with-resources)
|
||||
- [Java 8 New Features](http://www.baeldung.com/java-8-new-features)
|
||||
- [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips)
|
||||
- [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator)
|
||||
- [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams)
|
||||
- [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction)
|
||||
- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join)
|
||||
- [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java)
|
||||
- [How to Convert String to different data types in Java](http://www.baeldung.com/java-string-conversions)
|
||||
@@ -55,30 +47,20 @@
|
||||
- [The Traveling Salesman Problem in Java](http://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)
|
||||
- [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven)
|
||||
- [How to Design a Genetic Algorithm in Java](http://www.baeldung.com/java-genetic-algorithm)
|
||||
- [Guide to Java 8 groupingBy Collector](http://www.baeldung.com/java-groupingby-collector)
|
||||
- [Guide to WeakHashMap in Java](http://www.baeldung.com/java-weakhashmap)
|
||||
- [Strategy Design Pattern in Java 8](http://www.baeldung.com/java-strategy-pattern)
|
||||
- [Java 8 and Infinite Streams](http://www.baeldung.com/java-inifinite-streams)
|
||||
- [String Operations with Java Streams](http://www.baeldung.com/java-stream-operations-on-strings)
|
||||
- [Spring Security – Cache Control Headers](http://www.baeldung.com/spring-security-cache-control-headers)
|
||||
- [Basic Introduction to JMX](http://www.baeldung.com/java-management-extensions)
|
||||
- [AWS Lambda With Java](http://www.baeldung.com/java-aws-lambda)
|
||||
- [Introduction to Nashorn](http://www.baeldung.com/java-nashorn)
|
||||
- [Exceptions in Java 8 Lambda Expressions](http://www.baeldung.com/java-lambda-exceptions)
|
||||
- [Guide to the Guava BiMap](http://www.baeldung.com/guava-bimap)
|
||||
- [Iterable to Stream in Java](http://www.baeldung.com/java-iterable-to-stream)
|
||||
- [Java 8 Stream findFirst() vs. findAny()](http://www.baeldung.com/java-stream-findfirst-vs-findany)
|
||||
- [Chained Exceptions in Java](http://www.baeldung.com/java-chained-exceptions)
|
||||
- [The Java HashMap Under the Hood](http://www.baeldung.com/java-hashmap)
|
||||
- [A Guide to LinkedHashMap in Java](http://www.baeldung.com/java-linked-hashmap)
|
||||
- [A Guide to TreeMap in Java](http://www.baeldung.com/java-treemap)
|
||||
- [A Quick JUnit vs TestNG Comparison](http://www.baeldung.com/junit-vs-testng)
|
||||
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
|
||||
- [Guide to java.util.concurrent.Locks](http://www.baeldung.com/java-concurrent-locks)
|
||||
- [Java Primitive Conversions](http://www.baeldung.com/java-primitive-conversions)
|
||||
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
|
||||
- [Guide to Java 8 Comparator.comparing()](http://www.baeldung.com/java-8-comparator-comparing)
|
||||
- [Avoiding ConcurrentModificationException when iterating and removing](http://www.baeldung.com/avoiding-concurrentmodificationexception-when-iterating-and-removing)
|
||||
- [Removing all nulls from a List in Java](http://www.baeldung.com/java-remove-nulls-from-list)
|
||||
- [Removing all duplicates from a List in Java](http://www.baeldung.com/java-remove-duplicates-from-list)
|
||||
- [Using Math.pow in Java](http://www.baeldung.com/java-math-pow)
|
||||
@@ -96,7 +78,6 @@
|
||||
- [Iterating Over Enum Values in Java](http://www.baeldung.com/java-enum-iteration)
|
||||
- [Kotlin Java Interoperability](http://www.baeldung.com/kotlin-java-interoperability)
|
||||
- [Using Java MappedByteBuffer](http://www.baeldung.com/java-mapped-byte-buffer)
|
||||
- [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap)
|
||||
- [How to Round a Number to N Decimal Places in Java](http://www.baeldung.com/java-round-decimal-number)
|
||||
- [Changing Annotation Parameters At Runtime](http://www.baeldung.com/java-reflection-change-annotation-params)
|
||||
- [How to Find all Getters Returning Null](http://www.baeldung.com/java-getters-returning-null)
|
||||
@@ -117,8 +98,5 @@
|
||||
- [How to Remove the Last Character of a String?](http://www.baeldung.com/java-remove-last-character-of-string)
|
||||
- [ClassNotFoundException vs NoClassDefFoundError](http://www.baeldung.com/java-classnotfoundexception-and-noclassdeffounderror)
|
||||
- [Guide to UUID in Java](http://www.baeldung.com/java-uuid)
|
||||
- [How to Get the Last Element of a Stream in Java?](http://www.baeldung.com/java-stream-last-element)
|
||||
- [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char)
|
||||
- [Period and Duration in Java](http://www.baeldung.com/java-period-duration)
|
||||
- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro)
|
||||
- [Migrating to the New Java 8 Date Time API](http://www.baeldung.com/migrating-to-java-8-date-time-api)
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
package com.baeldung;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
|
||||
public interface Adder {
|
||||
|
||||
String addWithFunction(Function<String, String> f);
|
||||
|
||||
void addWithConsumer(Consumer<Integer> f);
|
||||
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.baeldung;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class AdderImpl implements Adder {
|
||||
|
||||
@Override
|
||||
public String addWithFunction(final Function<String, String> f) {
|
||||
return f.apply("Something ");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addWithConsumer(final Consumer<Integer> f) {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package com.baeldung;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface Bar {
|
||||
|
||||
String method(String string);
|
||||
|
||||
default String defaultMethod() {
|
||||
return "String from Bar";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package com.baeldung;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface Baz {
|
||||
|
||||
String method(String string);
|
||||
|
||||
default String defaultMethod() {
|
||||
return "String from Baz";
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.baeldung;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface Foo {
|
||||
|
||||
String method(String string);
|
||||
|
||||
default void defaultMethod() {
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package com.baeldung;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface FooExtended extends Baz, Bar {
|
||||
|
||||
@Override
|
||||
default String defaultMethod() {
|
||||
return Bar.super.defaultMethod();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
package com.baeldung;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
public class UseFoo {
|
||||
|
||||
private String value = "Enclosing scope value";
|
||||
|
||||
public String add(final String string, final Foo foo) {
|
||||
return foo.method(string);
|
||||
}
|
||||
|
||||
public String addWithStandardFI(final String string, final Function<String, String> fn) {
|
||||
return fn.apply(string);
|
||||
}
|
||||
|
||||
public String scopeExperiment() {
|
||||
final Foo fooIC = new Foo() {
|
||||
String value = "Inner class value";
|
||||
|
||||
@Override
|
||||
public String method(final String string) {
|
||||
return value;
|
||||
}
|
||||
};
|
||||
final String resultIC = fooIC.method("");
|
||||
|
||||
final Foo fooLambda = parameter -> {
|
||||
final String value = "Lambda value";
|
||||
return this.value;
|
||||
};
|
||||
final String resultLambda = fooLambda.method("");
|
||||
|
||||
return "Results: resultIC = " + resultIC + ", resultLambda = " + resultLambda;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
### Relevant Articles:
|
||||
- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro)
|
||||
@@ -1,16 +0,0 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalTime;
|
||||
import java.time.Period;
|
||||
|
||||
public class UseDuration {
|
||||
|
||||
public LocalTime modifyDates(LocalTime localTime, Duration duration) {
|
||||
return localTime.plus(duration);
|
||||
}
|
||||
|
||||
public Duration getDifferenceBetweenDates(LocalTime localTime1, LocalTime localTime2) {
|
||||
return Duration.between(localTime1, localTime2);
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.time.temporal.TemporalAdjusters;
|
||||
|
||||
class UseLocalDate {
|
||||
|
||||
LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth) {
|
||||
return LocalDate.of(year, month, dayOfMonth);
|
||||
}
|
||||
|
||||
LocalDate getLocalDateUsingParseMethod(String representation) {
|
||||
return LocalDate.parse(representation);
|
||||
}
|
||||
|
||||
LocalDate getLocalDateFromClock() {
|
||||
LocalDate localDate = LocalDate.now();
|
||||
return localDate;
|
||||
}
|
||||
|
||||
LocalDate getNextDay(LocalDate localDate) {
|
||||
return localDate.plusDays(1);
|
||||
}
|
||||
|
||||
LocalDate getPreviousDay(LocalDate localDate) {
|
||||
return localDate.minus(1, ChronoUnit.DAYS);
|
||||
}
|
||||
|
||||
DayOfWeek getDayOfWeek(LocalDate localDate) {
|
||||
DayOfWeek day = localDate.getDayOfWeek();
|
||||
return day;
|
||||
}
|
||||
|
||||
LocalDate getFirstDayOfMonth() {
|
||||
LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
|
||||
return firstDayOfMonth;
|
||||
}
|
||||
|
||||
LocalDateTime getStartOfDay(LocalDate localDate) {
|
||||
LocalDateTime startofDay = localDate.atStartOfDay();
|
||||
return startofDay;
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
|
||||
public class UseLocalTime {
|
||||
|
||||
LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds) {
|
||||
return LocalTime.of(hour, min, seconds);
|
||||
}
|
||||
|
||||
LocalTime getLocalTimeUsingParseMethod(String timeRepresentation) {
|
||||
return LocalTime.parse(timeRepresentation);
|
||||
}
|
||||
|
||||
private LocalTime getLocalTimeFromClock() {
|
||||
return LocalTime.now();
|
||||
}
|
||||
|
||||
LocalTime addAnHour(LocalTime localTime) {
|
||||
return localTime.plus(1, ChronoUnit.HOURS);
|
||||
}
|
||||
|
||||
int getHourFromLocalTime(LocalTime localTime) {
|
||||
return localTime.getHour();
|
||||
}
|
||||
|
||||
LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute) {
|
||||
return localTime.withMinute(minute);
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.Period;
|
||||
|
||||
class UsePeriod {
|
||||
|
||||
LocalDate modifyDates(LocalDate localDate, Period period) {
|
||||
return localDate.plus(period);
|
||||
}
|
||||
|
||||
Period getDifferenceBetweenDates(LocalDate localDate1, LocalDate localDate2) {
|
||||
return Period.between(localDate1, localDate2);
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
public class UseToInstant {
|
||||
|
||||
public LocalDateTime convertDateToLocalDate(Date date) {
|
||||
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
public LocalDateTime convertDateToLocalDate(Calendar calendar) {
|
||||
return LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault());
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
class UseZonedDateTime {
|
||||
|
||||
ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) {
|
||||
return ZonedDateTime.of(localDateTime, zoneId);
|
||||
}
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
package com.baeldung.doublecolon;
|
||||
|
||||
public class Computer {
|
||||
|
||||
private Integer age;
|
||||
private String color;
|
||||
private Integer healty;
|
||||
|
||||
Computer(final int age, final String color) {
|
||||
this.age = age;
|
||||
this.color = color;
|
||||
}
|
||||
|
||||
Computer(final Integer age, final String color, final Integer healty) {
|
||||
this.age = age;
|
||||
this.color = color;
|
||||
this.healty = healty;
|
||||
}
|
||||
|
||||
public Computer() {
|
||||
}
|
||||
|
||||
public Integer getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(final Integer age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
String getColor() {
|
||||
return color;
|
||||
}
|
||||
|
||||
public void setColor(final String color) {
|
||||
this.color = color;
|
||||
}
|
||||
|
||||
Integer getHealty() {
|
||||
return healty;
|
||||
}
|
||||
|
||||
void setHealty(final Integer healty) {
|
||||
this.healty = healty;
|
||||
}
|
||||
|
||||
public void turnOnPc() {
|
||||
System.out.println("Computer turned on");
|
||||
}
|
||||
|
||||
public void turnOffPc() {
|
||||
System.out.println("Computer turned off");
|
||||
}
|
||||
|
||||
public Double calculateValue(Double initialValue) {
|
||||
return initialValue / 1.50;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Computer{" + "age=" + age + ", color='" + color + '\'' + ", healty=" + healty + '}';
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final Computer computer = (Computer) o;
|
||||
|
||||
return (age != null ? age.equals(computer.age) : computer.age == null) && (color != null ? color.equals(computer.color) : computer.color == null);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = age != null ? age.hashCode() : 0;
|
||||
result = 31 * result + (color != null ? color.hashCode() : 0);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package com.baeldung.doublecolon;
|
||||
|
||||
import com.baeldung.doublecolon.function.ComputerPredicate;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class ComputerUtils {
|
||||
|
||||
static final ComputerPredicate after2010Predicate = (c) -> (c.getAge() > 2010);
|
||||
static final ComputerPredicate blackPredicate = (c) -> "black".equals(c.getColor());
|
||||
|
||||
public static List<Computer> filter(final List<Computer> inventory, final ComputerPredicate p) {
|
||||
|
||||
final List<Computer> result = new ArrayList<>();
|
||||
inventory.stream().filter(p::filter).forEach(result::add);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
static void repair(final Computer computer) {
|
||||
if (computer.getHealty() < 50) {
|
||||
computer.setHealty(100);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
package com.baeldung.doublecolon;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
public class MacbookPro extends Computer {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(MacbookPro.class);
|
||||
|
||||
public MacbookPro(int age, String color) {
|
||||
super(age, color);
|
||||
}
|
||||
|
||||
MacbookPro(Integer age, String color, Integer healty) {
|
||||
super(age, color, healty);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void turnOnPc() {
|
||||
LOG.debug("MacbookPro turned on");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void turnOffPc() {
|
||||
LOG.debug("MacbookPro turned off");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Double calculateValue(Double initialValue) {
|
||||
|
||||
Function<Double, Double> function = super::calculateValue;
|
||||
final Double pcValue = function.apply(initialValue);
|
||||
LOG.debug("First value is:" + pcValue);
|
||||
return pcValue + (initialValue / 10);
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.baeldung.doublecolon.function;
|
||||
|
||||
import com.baeldung.doublecolon.Computer;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface ComputerPredicate {
|
||||
|
||||
boolean filter(Computer c);
|
||||
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.doublecolon.function;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.Function;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface TriFunction<A, B, C, R> {
|
||||
|
||||
R apply(A a, B b, C c);
|
||||
|
||||
default <V> TriFunction<A, B, C, V> andThen(final Function<? super R, ? extends V> after) {
|
||||
Objects.requireNonNull(after);
|
||||
return (final A a, final B b, final C c) -> after.apply(apply(a, b, c));
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
package com.baeldung.java8.lambda.exceptions;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class LambdaExceptionWrappers {
|
||||
|
||||
public static Consumer<Integer> lambdaWrapper(Consumer<Integer> consumer) {
|
||||
return i -> {
|
||||
try {
|
||||
consumer.accept(i);
|
||||
} catch (ArithmeticException e) {
|
||||
System.err.println("Arithmetic Exception occured : " + e.getMessage());
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
static <T, E extends Exception> Consumer<T> consumerWrapper(Consumer<T> consumer, Class<E> clazz) {
|
||||
return i -> {
|
||||
try {
|
||||
consumer.accept(i);
|
||||
} catch (Exception ex) {
|
||||
try {
|
||||
E exCast = clazz.cast(ex);
|
||||
System.err.println("Exception occured : " + exCast.getMessage());
|
||||
} catch (ClassCastException ccEx) {
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public static <T> Consumer<T> throwingConsumerWrapper(ThrowingConsumer<T, Exception> throwingConsumer) {
|
||||
return i -> {
|
||||
try {
|
||||
throwingConsumer.accept(i);
|
||||
} catch (Exception ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public static <T, E extends Exception> Consumer<T> handlingConsumerWrapper(ThrowingConsumer<T, E> throwingConsumer, Class<E> exceptionClass) {
|
||||
return i -> {
|
||||
try {
|
||||
throwingConsumer.accept(i);
|
||||
} catch (Exception ex) {
|
||||
try {
|
||||
E exCast = exceptionClass.cast(ex);
|
||||
System.err.println("Exception occured : " + exCast.getMessage());
|
||||
} catch (ClassCastException ccEx) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package com.baeldung.java8.lambda.exceptions;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface ThrowingConsumer<T, E extends Exception> {
|
||||
|
||||
void accept(T t) throws E;
|
||||
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
public class Address {
|
||||
|
||||
private String street;
|
||||
|
||||
public String getStreet() {
|
||||
return street;
|
||||
}
|
||||
|
||||
public void setStreet(String street) {
|
||||
this.street = street;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
public class CustomException extends RuntimeException {
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class Detail {
|
||||
|
||||
private static final List<String> PARTS = Arrays.asList("turbine", "pump");
|
||||
|
||||
public List<String> getParts() {
|
||||
return PARTS;
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class OptionalAddress {
|
||||
|
||||
private String street;
|
||||
|
||||
public Optional<String> getStreet() {
|
||||
return Optional.ofNullable(street);
|
||||
}
|
||||
|
||||
public void setStreet(String street) {
|
||||
this.street = street;
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class OptionalUser {
|
||||
|
||||
private OptionalAddress address;
|
||||
|
||||
public Optional<OptionalAddress> getAddress() {
|
||||
return Optional.of(address);
|
||||
}
|
||||
|
||||
public void setAddress(OptionalAddress address) {
|
||||
this.address = address;
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
public class Person {
|
||||
private String name;
|
||||
private Integer age;
|
||||
|
||||
public Person(String name, int age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Integer getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(Integer age) {
|
||||
this.age = age;
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class User {
|
||||
|
||||
private String name;
|
||||
|
||||
private Address address;
|
||||
|
||||
public Address getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(Address address) {
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public static boolean isRealUser(User user) {
|
||||
return true;
|
||||
}
|
||||
|
||||
public String getOrThrow() {
|
||||
String value = null;
|
||||
Optional<String> valueOpt = Optional.ofNullable(value);
|
||||
String result = valueOpt.orElseThrow(CustomException::new).toUpperCase();
|
||||
return result;
|
||||
}
|
||||
|
||||
public boolean isLegalName(String name) {
|
||||
return name.length() > 3 && name.length() < 16;
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
public interface Vehicle {
|
||||
|
||||
void moveTo(long altitude, long longitude);
|
||||
|
||||
static String producer() {
|
||||
return "N&F Vehicles";
|
||||
}
|
||||
|
||||
default long[] startPosition() {
|
||||
return new long[] { 23, 15 };
|
||||
}
|
||||
|
||||
default String getOverview() {
|
||||
return "ATV made by " + producer();
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
public class VehicleImpl implements Vehicle {
|
||||
|
||||
@Override
|
||||
public void moveTo(long altitude, long longitude) {
|
||||
// do nothing
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
package com.baeldung.java_8_features.groupingby;
|
||||
|
||||
public class BlogPost {
|
||||
private String title;
|
||||
private String author;
|
||||
private BlogPostType type;
|
||||
private int likes;
|
||||
|
||||
public BlogPost(String title, String author, BlogPostType type, int likes) {
|
||||
this.title = title;
|
||||
this.author = author;
|
||||
this.type = type;
|
||||
this.likes = likes;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public String getAuthor() {
|
||||
return author;
|
||||
}
|
||||
|
||||
public BlogPostType getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public int getLikes() {
|
||||
return likes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "BlogPost{" + "title='" + title + '\'' + ", type=" + type + ", likes=" + likes + '}';
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package com.baeldung.java_8_features.groupingby;
|
||||
|
||||
public enum BlogPostType {
|
||||
NEWS, REVIEW, GUIDE
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package com.baeldung.optional;
|
||||
|
||||
public class Modem {
|
||||
private Double price;
|
||||
|
||||
public Modem(Double price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public Double getPrice() {
|
||||
return price;
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
package com.baeldung.optional;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class Person {
|
||||
private String name;
|
||||
private int age;
|
||||
private String password;
|
||||
|
||||
public Person(String name, int age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public Optional<String> getName() {
|
||||
return Optional.ofNullable(name);
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Optional<Integer> getAge() {
|
||||
return Optional.ofNullable(age);
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public Optional<String> getPassword() {
|
||||
return Optional.ofNullable(password);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package com.baeldung.strategy;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
public class ChristmasDiscounter implements Discounter {
|
||||
|
||||
@Override
|
||||
public BigDecimal apply(BigDecimal amount) {
|
||||
return amount.multiply(BigDecimal.valueOf(0.9));
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package com.baeldung.strategy;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.function.UnaryOperator;
|
||||
|
||||
public interface Discounter extends UnaryOperator<BigDecimal> {
|
||||
|
||||
default Discounter combine(Discounter after) {
|
||||
return value -> after.apply(this.apply(value));
|
||||
}
|
||||
|
||||
static Discounter christmas() {
|
||||
return (amount) -> amount.multiply(BigDecimal.valueOf(0.9));
|
||||
}
|
||||
|
||||
static Discounter newYear() {
|
||||
return (amount) -> amount.multiply(BigDecimal.valueOf(0.8));
|
||||
}
|
||||
|
||||
static Discounter easter() {
|
||||
return (amount) -> amount.multiply(BigDecimal.valueOf(0.5));
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package com.baeldung.strategy;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
public class EasterDiscounter implements Discounter {
|
||||
|
||||
@Override
|
||||
public BigDecimal apply(BigDecimal amount) {
|
||||
return amount.multiply(BigDecimal.valueOf(0.5));
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class InfiniteStreams {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(InfiniteStreams.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
doWhileOldWay();
|
||||
|
||||
doWhileStreamWay();
|
||||
|
||||
}
|
||||
|
||||
private static void doWhileOldWay() {
|
||||
|
||||
int i = 0;
|
||||
while (i < 10) {
|
||||
LOG.debug("{}", i);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
private static void doWhileStreamWay() {
|
||||
Stream<Integer> integers = Stream.iterate(0, i -> i + 1);
|
||||
integers.limit(10).forEach(System.out::println);
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class StreamApi {
|
||||
|
||||
public static String getLastElementUsingReduce(List<String> valueList) {
|
||||
Stream<String> stream = valueList.stream();
|
||||
return stream.reduce((first, second) -> second).orElse(null);
|
||||
}
|
||||
|
||||
public static Integer getInfiniteStreamLastElementUsingReduce() {
|
||||
Stream<Integer> stream = Stream.iterate(0, i -> i + 1);
|
||||
return stream.limit(20).reduce((first, second) -> second).orElse(null);
|
||||
}
|
||||
|
||||
public static String getLastElementUsingSkip(List<String> valueList) {
|
||||
long count = valueList.stream().count();
|
||||
Stream<String> stream = valueList.stream();
|
||||
return stream.skip(count - 1).findFirst().orElse(null);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
package com.baeldung.streamApi;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Created by Alex Vengr
|
||||
*/
|
||||
public class Product {
|
||||
|
||||
private int price;
|
||||
|
||||
private String name;
|
||||
|
||||
private boolean utilize;
|
||||
|
||||
public Product(int price, String name) {
|
||||
this(price);
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Product(int price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public Product() {
|
||||
}
|
||||
|
||||
public int getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(int price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public static Stream<String> streamOf(List<String> list) {
|
||||
return (list == null || list.isEmpty()) ? Stream.empty() : list.stream();
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class JoinerSplitter {
|
||||
|
||||
public static String join ( String[] arrayOfString ) {
|
||||
return Arrays.asList(arrayOfString)
|
||||
.stream()
|
||||
.map(x -> x)
|
||||
.collect(Collectors.joining(","));
|
||||
}
|
||||
|
||||
public static String joinWithPrefixPostFix ( String[] arrayOfString ) {
|
||||
return Arrays.asList(arrayOfString)
|
||||
.stream()
|
||||
.map(x -> x)
|
||||
.collect(Collectors.joining(",","[","]"));
|
||||
}
|
||||
|
||||
public static List<String> split ( String str ) {
|
||||
return Stream.of(str.split(","))
|
||||
.map (elem -> new String(elem))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static List<Character> splitToListOfChar ( String str ) {
|
||||
return str.chars()
|
||||
.mapToObj(item -> (char) item)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package com.baeldung.temporaladjuster;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.temporal.ChronoField;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.time.temporal.Temporal;
|
||||
import java.time.temporal.TemporalAdjuster;
|
||||
|
||||
public class CustomTemporalAdjuster implements TemporalAdjuster {
|
||||
|
||||
@Override
|
||||
public Temporal adjustInto(Temporal temporal) {
|
||||
switch (DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK))) {
|
||||
case FRIDAY:
|
||||
return temporal.plus(3, ChronoUnit.DAYS);
|
||||
case SATURDAY:
|
||||
return temporal.plus(2, ChronoUnit.DAYS);
|
||||
default:
|
||||
return temporal.plus(1, ChronoUnit.DAYS);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,210 +0,0 @@
|
||||
package com.baeldung.collectors;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.Sets;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.DoubleSummaryStatistics;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.BinaryOperator;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collector;
|
||||
|
||||
import static com.google.common.collect.Sets.newHashSet;
|
||||
import static java.util.stream.Collectors.averagingDouble;
|
||||
import static java.util.stream.Collectors.collectingAndThen;
|
||||
import static java.util.stream.Collectors.counting;
|
||||
import static java.util.stream.Collectors.groupingBy;
|
||||
import static java.util.stream.Collectors.joining;
|
||||
import static java.util.stream.Collectors.maxBy;
|
||||
import static java.util.stream.Collectors.partitioningBy;
|
||||
import static java.util.stream.Collectors.summarizingDouble;
|
||||
import static java.util.stream.Collectors.summingDouble;
|
||||
import static java.util.stream.Collectors.toCollection;
|
||||
import static java.util.stream.Collectors.toList;
|
||||
import static java.util.stream.Collectors.toMap;
|
||||
import static java.util.stream.Collectors.toSet;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
public class Java8CollectorsUnitTest {
|
||||
|
||||
private final List<String> givenList = Arrays.asList("a", "bb", "ccc", "dd");
|
||||
|
||||
@Test
|
||||
public void whenCollectingToList_shouldCollectToList() throws Exception {
|
||||
final List<String> result = givenList.stream().collect(toList());
|
||||
|
||||
assertThat(result).containsAll(givenList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToList_shouldCollectToSet() throws Exception {
|
||||
final Set<String> result = givenList.stream().collect(toSet());
|
||||
|
||||
assertThat(result).containsAll(givenList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToCollection_shouldCollectToCollection() throws Exception {
|
||||
final List<String> result = givenList.stream().collect(toCollection(LinkedList::new));
|
||||
|
||||
assertThat(result).containsAll(givenList).isInstanceOf(LinkedList.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception {
|
||||
assertThatThrownBy(() -> {
|
||||
givenList.stream().collect(toCollection(ImmutableList::of));
|
||||
}).isInstanceOf(UnsupportedOperationException.class);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToMap_shouldCollectToMap() throws Exception {
|
||||
final Map<String, Integer> result = givenList.stream().collect(toMap(Function.identity(), String::length));
|
||||
|
||||
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToMap_shouldCollectToMapMerging() throws Exception {
|
||||
final Map<String, Integer> result = givenList.stream().collect(toMap(Function.identity(), String::length, (i1, i2) -> i1));
|
||||
|
||||
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingAndThen_shouldCollect() throws Exception {
|
||||
final List<String> result = givenList.stream().collect(collectingAndThen(toList(), ImmutableList::copyOf));
|
||||
|
||||
assertThat(result).containsAll(givenList).isInstanceOf(ImmutableList.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJoining_shouldJoin() throws Exception {
|
||||
final String result = givenList.stream().collect(joining());
|
||||
|
||||
assertThat(result).isEqualTo("abbcccdd");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception {
|
||||
final String result = givenList.stream().collect(joining(" "));
|
||||
|
||||
assertThat(result).isEqualTo("a bb ccc dd");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception {
|
||||
final String result = givenList.stream().collect(joining(" ", "PRE-", "-POST"));
|
||||
|
||||
assertThat(result).isEqualTo("PRE-a bb ccc dd-POST");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPartitioningBy_shouldPartition() throws Exception {
|
||||
final Map<Boolean, List<String>> result = givenList.stream().collect(partitioningBy(s -> s.length() > 2));
|
||||
|
||||
assertThat(result).containsKeys(true, false).satisfies(booleanListMap -> {
|
||||
assertThat(booleanListMap.get(true)).contains("ccc");
|
||||
|
||||
assertThat(booleanListMap.get(false)).contains("a", "bb", "dd");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCounting_shouldCount() throws Exception {
|
||||
final Long result = givenList.stream().collect(counting());
|
||||
|
||||
assertThat(result).isEqualTo(4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSummarizing_shouldSummarize() throws Exception {
|
||||
final DoubleSummaryStatistics result = givenList.stream().collect(summarizingDouble(String::length));
|
||||
|
||||
assertThat(result.getAverage()).isEqualTo(2);
|
||||
assertThat(result.getCount()).isEqualTo(4);
|
||||
assertThat(result.getMax()).isEqualTo(3);
|
||||
assertThat(result.getMin()).isEqualTo(1);
|
||||
assertThat(result.getSum()).isEqualTo(8);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAveraging_shouldAverage() throws Exception {
|
||||
final Double result = givenList.stream().collect(averagingDouble(String::length));
|
||||
|
||||
assertThat(result).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSumming_shouldSum() throws Exception {
|
||||
final Double result = givenList.stream().filter(i -> true).collect(summingDouble(String::length));
|
||||
|
||||
assertThat(result).isEqualTo(8);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMaxingBy_shouldMaxBy() throws Exception {
|
||||
final Optional<String> result = givenList.stream().collect(maxBy(Comparator.naturalOrder()));
|
||||
|
||||
assertThat(result).isPresent().hasValue("dd");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGroupingBy_shouldGroupBy() throws Exception {
|
||||
final Map<Integer, Set<String>> result = givenList.stream().collect(groupingBy(String::length, toSet()));
|
||||
|
||||
assertThat(result).containsEntry(1, newHashSet("a")).containsEntry(2, newHashSet("bb", "dd")).containsEntry(3, newHashSet("ccc"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingCustomCollector_shouldCollect() throws Exception {
|
||||
final ImmutableSet<String> result = givenList.stream().collect(toImmutableSet());
|
||||
|
||||
assertThat(result).isInstanceOf(ImmutableSet.class).contains("a", "bb", "ccc", "dd");
|
||||
|
||||
}
|
||||
|
||||
private static <T> ImmutableSetCollector<T> toImmutableSet() {
|
||||
return new ImmutableSetCollector<>();
|
||||
}
|
||||
|
||||
private static class ImmutableSetCollector<T> implements Collector<T, ImmutableSet.Builder<T>, ImmutableSet<T>> {
|
||||
|
||||
@Override
|
||||
public Supplier<ImmutableSet.Builder<T>> supplier() {
|
||||
return ImmutableSet::builder;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BiConsumer<ImmutableSet.Builder<T>, T> accumulator() {
|
||||
return ImmutableSet.Builder::add;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BinaryOperator<ImmutableSet.Builder<T>> combiner() {
|
||||
return (left, right) -> left.addAll(right.build());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Function<ImmutableSet.Builder<T>, ImmutableSet<T>> finisher() {
|
||||
return ImmutableSet.Builder::build;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Characteristics> characteristics() {
|
||||
return Sets.immutableEnumSet(Characteristics.UNORDERED);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package com.baeldung.dateapi;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
import java.util.TimeZone;
|
||||
|
||||
public class ConversionExample {
|
||||
public static void main(String[] args) {
|
||||
Instant instantFromCalendar = GregorianCalendar.getInstance().toInstant();
|
||||
ZonedDateTime zonedDateTimeFromCalendar = new GregorianCalendar().toZonedDateTime();
|
||||
Date dateFromInstant = Date.from(Instant.now());
|
||||
GregorianCalendar calendarFromZonedDateTime = GregorianCalendar.from(ZonedDateTime.now());
|
||||
Instant instantFromDate = new Date().toInstant();
|
||||
ZoneId zoneIdFromTimeZone = TimeZone.getTimeZone("PST").toZoneId();
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package com.baeldung.dateapi;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class JavaDurationUnitTest {
|
||||
|
||||
@Test
|
||||
public void test2() {
|
||||
Instant start = Instant.parse("2017-10-03T10:15:30.00Z");
|
||||
Instant end = Instant.parse("2017-10-03T10:16:30.00Z");
|
||||
|
||||
Duration duration = Duration.between(start, end);
|
||||
|
||||
assertFalse(duration.isNegative());
|
||||
|
||||
assertEquals(60, duration.getSeconds());
|
||||
assertEquals(1, duration.toMinutes());
|
||||
|
||||
Duration fromDays = Duration.ofDays(1);
|
||||
assertEquals(86400, fromDays.getSeconds());
|
||||
|
||||
Duration fromMinutes = Duration.ofMinutes(60);
|
||||
assertEquals(1, fromMinutes.toHours());
|
||||
|
||||
assertEquals(120, duration.plusSeconds(60).getSeconds());
|
||||
assertEquals(30, duration.minusSeconds(30).getSeconds());
|
||||
|
||||
assertEquals(120, duration.plus(60, ChronoUnit.SECONDS).getSeconds());
|
||||
assertEquals(30, duration.minus(30, ChronoUnit.SECONDS).getSeconds());
|
||||
|
||||
Duration fromChar1 = Duration.parse("P1DT1H10M10.5S");
|
||||
Duration fromChar2 = Duration.parse("PT10M");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package com.baeldung.dateapi;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.Period;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
||||
public class JavaPeriodUnitTest {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(JavaPeriodUnitTest.class);
|
||||
|
||||
@Test
|
||||
public void whenTestPeriod_thenOk() {
|
||||
|
||||
LocalDate startDate = LocalDate.of(2015, 2, 15);
|
||||
LocalDate endDate = LocalDate.of(2017, 1, 21);
|
||||
|
||||
Period period = Period.between(startDate, endDate);
|
||||
|
||||
LOG.info(String.format("Years:%d months:%d days:%d", period.getYears(), period.getMonths(), period.getDays()));
|
||||
|
||||
assertFalse(period.isNegative());
|
||||
assertEquals(56, period.plusDays(50).getDays());
|
||||
assertEquals(9, period.minusMonths(2).getMonths());
|
||||
|
||||
Period fromUnits = Period.of(3, 10, 10);
|
||||
Period fromDays = Period.ofDays(50);
|
||||
Period fromMonths = Period.ofMonths(5);
|
||||
Period fromYears = Period.ofYears(10);
|
||||
Period fromWeeks = Period.ofWeeks(40);
|
||||
|
||||
assertEquals(280, fromWeeks.getDays());
|
||||
|
||||
Period fromCharYears = Period.parse("P2Y");
|
||||
assertEquals(2, fromCharYears.getYears());
|
||||
Period fromCharUnits = Period.parse("P2Y3M5D");
|
||||
assertEquals(5, fromCharUnits.getDays());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
package com.baeldung.dateapi;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.time.Month;
|
||||
import java.time.YearMonth;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class JavaUtilTimeUnitTest {
|
||||
|
||||
@Test
|
||||
public void currentTime() {
|
||||
final LocalDate now = LocalDate.now();
|
||||
|
||||
System.out.println(now);
|
||||
// there is not much to test here
|
||||
}
|
||||
|
||||
@Test
|
||||
public void specificTime() {
|
||||
LocalDate birthDay = LocalDate.of(1990, Month.DECEMBER, 15);
|
||||
|
||||
System.out.println(birthDay);
|
||||
// there is not much to test here
|
||||
}
|
||||
|
||||
@Test
|
||||
public void extractMonth() {
|
||||
Month month = LocalDate.of(1990, Month.DECEMBER, 15).getMonth();
|
||||
|
||||
assertThat(month).isEqualTo(Month.DECEMBER);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void subtractTime() {
|
||||
LocalDateTime fiveHoursBefore = LocalDateTime.of(1990, Month.DECEMBER, 15, 15, 0).minusHours(5);
|
||||
|
||||
assertThat(fiveHoursBefore.getHour()).isEqualTo(10);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void alterField() {
|
||||
LocalDateTime inJune = LocalDateTime.of(1990, Month.DECEMBER, 15, 15, 0).with(Month.JUNE);
|
||||
|
||||
assertThat(inJune.getMonth()).isEqualTo(Month.JUNE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void truncate() {
|
||||
LocalTime truncated = LocalTime.of(15, 12, 34).truncatedTo(ChronoUnit.HOURS);
|
||||
|
||||
assertThat(truncated).isEqualTo(LocalTime.of(15, 0, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getTimeSpan() {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
LocalDateTime hourLater = now.plusHours(1);
|
||||
Duration span = Duration.between(now, hourLater);
|
||||
|
||||
assertThat(span).isEqualTo(Duration.ofHours(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void formatAndParse() throws ParseException {
|
||||
LocalDate someDate = LocalDate.of(2016, 12, 7);
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
String formattedDate = someDate.format(formatter);
|
||||
LocalDate parsedDate = LocalDate.parse(formattedDate, formatter);
|
||||
|
||||
assertThat(formattedDate).isEqualTo("2016-12-07");
|
||||
assertThat(parsedDate).isEqualTo(someDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void daysInMonth() {
|
||||
int daysInMonth = YearMonth.of(1990, 2).lengthOfMonth();
|
||||
|
||||
assertThat(daysInMonth).isEqualTo(28);
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalTime;
|
||||
import java.time.Month;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class UseLocalDateTimeUnitTest {
|
||||
|
||||
UseLocalDateTime useLocalDateTime = new UseLocalDateTime();
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingParse_thenLocalDateTime() {
|
||||
assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30")
|
||||
.toLocalDate());
|
||||
assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30")
|
||||
.toLocalTime());
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class UseLocalDateUnitTest {
|
||||
|
||||
UseLocalDate useLocalDate = new UseLocalDate();
|
||||
|
||||
@Test
|
||||
public void givenValues_whenUsingFactoryOf_thenLocalDate() {
|
||||
assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10)
|
||||
.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingParse_thenLocalDate() {
|
||||
assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10")
|
||||
.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingClock_thenLocalDate() {
|
||||
assertEquals(LocalDate.now(), useLocalDate.getLocalDateFromClock());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDate_whenUsingPlus_thenNextDay() {
|
||||
assertEquals(LocalDate.now()
|
||||
.plusDays(1), useLocalDate.getNextDay(LocalDate.now()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDate_whenUsingMinus_thenPreviousDay() {
|
||||
assertEquals(LocalDate.now()
|
||||
.minusDays(1), useLocalDate.getPreviousDay(LocalDate.now()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenToday_whenUsingGetDayOfWeek_thenDayOfWeek() {
|
||||
assertEquals(DayOfWeek.SUNDAY, useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth() {
|
||||
assertEquals(1, useLocalDate.getFirstDayOfMonth()
|
||||
.getDayOfMonth());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalDate_whenUsingAtStartOfDay_thenReturnMidnight() {
|
||||
assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"), useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22")));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalTime;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class UseLocalTimeUnitTest {
|
||||
|
||||
UseLocalTime useLocalTime = new UseLocalTime();
|
||||
|
||||
@Test
|
||||
public void givenValues_whenUsingFactoryOf_thenLocalTime() {
|
||||
Assert.assertEquals("07:07:07", useLocalTime.getLocalTimeUsingFactoryOfMethod(7, 7, 7).toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingParse_thenLocalTime() {
|
||||
Assert.assertEquals("06:30", useLocalTime.getLocalTimeUsingParseMethod("06:30").toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTime_whenAddHour_thenLocalTime() {
|
||||
Assert.assertEquals("07:30", useLocalTime.addAnHour(LocalTime.of(6, 30)).toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getHourFromLocalTime() {
|
||||
Assert.assertEquals(1, useLocalTime.getHourFromLocalTime(LocalTime.of(1, 1)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getLocalTimeWithMinuteSetToValue() {
|
||||
Assert.assertEquals(LocalTime.of(10, 20), useLocalTime.getLocalTimeWithMinuteSetToValue(LocalTime.of(10, 10), 20));
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.Period;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class UsePeriodUnitTest {
|
||||
UsePeriod usingPeriod = new UsePeriod();
|
||||
|
||||
@Test
|
||||
public void givenPeriodAndLocalDate_thenCalculateModifiedDate() {
|
||||
Period period = Period.ofDays(1);
|
||||
LocalDate localDate = LocalDate.parse("2007-05-10");
|
||||
Assert.assertEquals(localDate.plusDays(1), usingPeriod.modifyDates(localDate, period));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDates_thenGetPeriod() {
|
||||
LocalDate localDate1 = LocalDate.parse("2007-05-10");
|
||||
LocalDate localDate2 = LocalDate.parse("2007-05-15");
|
||||
|
||||
Assert.assertEquals(Period.ofDays(5), usingPeriod.getDifferenceBetweenDates(localDate1, localDate2));
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class UseZonedDateTimeUnitTest {
|
||||
|
||||
UseZonedDateTime zonedDateTime = new UseZonedDateTime();
|
||||
|
||||
@Test
|
||||
public void givenZoneId_thenZonedDateTime() {
|
||||
ZoneId zoneId = ZoneId.of("Europe/Paris");
|
||||
ZonedDateTime zonedDatetime = zonedDateTime.getZonedDateTime(LocalDateTime.parse("2016-05-20T06:30"), zoneId);
|
||||
Assert.assertEquals(zoneId, ZoneId.from(zonedDatetime));
|
||||
}
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
package com.baeldung.doublecolon;
|
||||
|
||||
import com.baeldung.doublecolon.function.TriFunction;
|
||||
import org.junit.After;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.function.BiFunction;
|
||||
|
||||
import static com.baeldung.doublecolon.ComputerUtils.*;
|
||||
|
||||
public class ComputerUtilsUnitTest {
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConstructorReference() {
|
||||
|
||||
Computer c1 = new Computer(2015, "white");
|
||||
Computer c2 = new Computer(2009, "black");
|
||||
Computer c3 = new Computer(2014, "black");
|
||||
|
||||
BiFunction<Integer, String, Computer> c4Function = Computer::new;
|
||||
Computer c4 = c4Function.apply(2013, "white");
|
||||
BiFunction<Integer, String, Computer> c5Function = Computer::new;
|
||||
Computer c5 = c5Function.apply(2010, "black");
|
||||
BiFunction<Integer, String, Computer> c6Function = Computer::new;
|
||||
Computer c6 = c6Function.apply(2008, "black");
|
||||
|
||||
List<Computer> inventory = Arrays.asList(c1, c2, c3, c4, c5, c6);
|
||||
|
||||
List<Computer> blackComputer = filter(inventory, blackPredicate);
|
||||
Assert.assertEquals("The black Computers are: ", blackComputer.size(), 4);
|
||||
|
||||
List<Computer> after2010Computer = filter(inventory, after2010Predicate);
|
||||
Assert.assertEquals("The Computer bought after 2010 are: ", after2010Computer.size(), 3);
|
||||
|
||||
List<Computer> before2011Computer = filter(inventory, c -> c.getAge() < 2011);
|
||||
Assert.assertEquals("The Computer bought before 2011 are: ", before2011Computer.size(), 3);
|
||||
|
||||
inventory.sort(Comparator.comparing(Computer::getAge));
|
||||
|
||||
Assert.assertEquals("Oldest Computer in inventory", c6, inventory.get(0));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStaticMethodReference() {
|
||||
|
||||
Computer c1 = new Computer(2015, "white", 35);
|
||||
Computer c2 = new Computer(2009, "black", 65);
|
||||
TriFunction<Integer, String, Integer, Computer> c6Function = Computer::new;
|
||||
Computer c3 = c6Function.apply(2008, "black", 90);
|
||||
|
||||
List<Computer> inventory = Arrays.asList(c1, c2, c3);
|
||||
inventory.forEach(ComputerUtils::repair);
|
||||
|
||||
Assert.assertEquals("Computer repaired", new Integer(100), c1.getHealty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInstanceMethodArbitraryObjectParticularType() {
|
||||
|
||||
Computer c1 = new Computer(2015, "white", 35);
|
||||
Computer c2 = new MacbookPro(2009, "black", 65);
|
||||
List<Computer> inventory = Arrays.asList(c1, c2);
|
||||
inventory.forEach(Computer::turnOnPc);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSuperMethodReference() {
|
||||
|
||||
final TriFunction<Integer, String, Integer, MacbookPro> integerStringIntegerObjectTriFunction = MacbookPro::new;
|
||||
final MacbookPro macbookPro = integerStringIntegerObjectTriFunction.apply(2010, "black", 100);
|
||||
Double initialValue = 999.99;
|
||||
final Double actualValue = macbookPro.calculateValue(initialValue);
|
||||
Assert.assertEquals(766.659, actualValue, 0.0);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,187 +0,0 @@
|
||||
package com.baeldung.functionalinterface;
|
||||
|
||||
import com.google.common.util.concurrent.Uninterruptibles;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class FunctionalInterfaceUnitTest {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(FunctionalInterfaceUnitTest.class);
|
||||
|
||||
@Test
|
||||
public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() {
|
||||
Map<String, Integer> nameMap = new HashMap<>();
|
||||
Integer value = nameMap.computeIfAbsent("John", String::length);
|
||||
|
||||
assertEquals(new Integer(4), nameMap.get("John"));
|
||||
assertEquals(new Integer(4), value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPassingMethodReferenceToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() {
|
||||
Map<String, Integer> nameMap = new HashMap<>();
|
||||
Integer value = nameMap.computeIfAbsent("John", String::length);
|
||||
|
||||
assertEquals(new Integer(4), nameMap.get("John"));
|
||||
assertEquals(new Integer(4), value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCustomFunctionalInterfaceForPrimitives_thenCanUseItAsLambda() {
|
||||
|
||||
short[] array = { (short) 1, (short) 2, (short) 3 };
|
||||
byte[] transformedArray = transformArray(array, s -> (byte) (s * 2));
|
||||
|
||||
byte[] expectedArray = { (byte) 2, (byte) 4, (byte) 6 };
|
||||
assertArrayEquals(expectedArray, transformedArray);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingBiFunction_thenCanUseItToReplaceMapValues() {
|
||||
Map<String, Integer> salaries = new HashMap<>();
|
||||
salaries.put("John", 40000);
|
||||
salaries.put("Freddy", 30000);
|
||||
salaries.put("Samuel", 50000);
|
||||
|
||||
salaries.replaceAll((name, oldValue) -> name.equals("Freddy") ? oldValue : oldValue + 10000);
|
||||
|
||||
assertEquals(new Integer(50000), salaries.get("John"));
|
||||
assertEquals(new Integer(30000), salaries.get("Freddy"));
|
||||
assertEquals(new Integer(60000), salaries.get("Samuel"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPassingLambdaToThreadConstructor_thenLambdaInferredToRunnable() {
|
||||
Thread thread = new Thread(() -> LOG.debug("Hello From Another Thread"));
|
||||
thread.start();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingSupplierToGenerateNumbers_thenCanUseItInStreamGenerate() {
|
||||
|
||||
int[] fibs = { 0, 1 };
|
||||
Stream<Integer> fibonacci = Stream.generate(() -> {
|
||||
int result = fibs[1];
|
||||
int fib3 = fibs[0] + fibs[1];
|
||||
fibs[0] = fibs[1];
|
||||
fibs[1] = fib3;
|
||||
return result;
|
||||
});
|
||||
|
||||
List<Integer> fibonacci5 = fibonacci.limit(5)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertEquals(new Integer(1), fibonacci5.get(0));
|
||||
assertEquals(new Integer(1), fibonacci5.get(1));
|
||||
assertEquals(new Integer(2), fibonacci5.get(2));
|
||||
assertEquals(new Integer(3), fibonacci5.get(3));
|
||||
assertEquals(new Integer(5), fibonacci5.get(4));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingConsumerInForEach_thenConsumerExecutesForEachListElement() {
|
||||
List<String> names = Arrays.asList("John", "Freddy", "Samuel");
|
||||
names.forEach(name -> LOG.debug("Hello, " + name));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingBiConsumerInForEach_thenConsumerExecutesForEachMapElement() {
|
||||
Map<String, Integer> ages = new HashMap<>();
|
||||
ages.put("John", 25);
|
||||
ages.put("Freddy", 24);
|
||||
ages.put("Samuel", 30);
|
||||
|
||||
ages.forEach((name, age) -> LOG.debug(name + " is " + age + " years old"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingPredicateInFilter_thenListValuesAreFilteredOut() {
|
||||
List<String> names = Arrays.asList("Angela", "Aaron", "Bob", "Claire", "David");
|
||||
|
||||
List<String> namesWithA = names.stream()
|
||||
.filter(name -> name.startsWith("A"))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertEquals(2, namesWithA.size());
|
||||
assertTrue(namesWithA.contains("Angela"));
|
||||
assertTrue(namesWithA.contains("Aaron"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingUnaryOperatorWithReplaceAll_thenAllValuesInTheListAreReplaced() {
|
||||
List<String> names = Arrays.asList("bob", "josh", "megan");
|
||||
|
||||
names.replaceAll(String::toUpperCase);
|
||||
|
||||
assertEquals("BOB", names.get(0));
|
||||
assertEquals("JOSH", names.get(1));
|
||||
assertEquals("MEGAN", names.get(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingBinaryOperatorWithStreamReduce_thenResultIsSumOfValues() {
|
||||
|
||||
List<Integer> values = Arrays.asList(3, 5, 8, 9, 12);
|
||||
|
||||
int sum = values.stream()
|
||||
.reduce(0, (i1, i2) -> i1 + i2);
|
||||
|
||||
assertEquals(37, sum);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenComposingTwoFunctions_thenFunctionsExecuteSequentially() {
|
||||
|
||||
Function<Integer, String> intToString = Object::toString;
|
||||
Function<String, String> quote = s -> "'" + s + "'";
|
||||
|
||||
Function<Integer, String> quoteIntToString = quote.compose(intToString);
|
||||
|
||||
assertEquals("'5'", quoteIntToString.apply(5));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingSupplierToGenerateValue_thenValueIsGeneratedLazily() {
|
||||
|
||||
Supplier<Double> lazyValue = () -> {
|
||||
Uninterruptibles.sleepUninterruptibly(1000, TimeUnit.MILLISECONDS);
|
||||
return 9d;
|
||||
};
|
||||
|
||||
double valueSquared = squareLazy(lazyValue);
|
||||
|
||||
assertEquals(81d, valueSquared, 0);
|
||||
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package com.baeldung.functionalinterface;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface ShortToByteFunction {
|
||||
|
||||
byte applyAsByte(short s);
|
||||
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
package com.baeldung.java8;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class Java8CollectionCleanupUnitTest {
|
||||
|
||||
// tests -
|
||||
|
||||
@Test
|
||||
public void givenListContainsNulls_whenFilteringParallel_thenCorrect() {
|
||||
final List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null);
|
||||
final List<Integer> listWithoutNulls = list.parallelStream().filter(Objects::nonNull).collect(Collectors.toList());
|
||||
|
||||
assertThat(listWithoutNulls, hasSize(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListContainsNulls_whenFilteringSerial_thenCorrect() {
|
||||
final List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null);
|
||||
final List<Integer> listWithoutNulls = list.stream().filter(Objects::nonNull).collect(Collectors.toList());
|
||||
|
||||
assertThat(listWithoutNulls, hasSize(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListContainsNulls_whenRemovingNullsWithRemoveIf_thenCorrect() {
|
||||
final List<Integer> listWithoutNulls = Lists.newArrayList(null, 1, 2, null, 3, null);
|
||||
listWithoutNulls.removeIf(Objects::isNull);
|
||||
|
||||
assertThat(listWithoutNulls, hasSize(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListContainsDuplicates_whenRemovingDuplicatesWithJava8_thenCorrect() {
|
||||
final List<Integer> listWithDuplicates = Lists.newArrayList(1, 1, 2, 2, 3, 3);
|
||||
final List<Integer> listWithoutDuplicates = listWithDuplicates.parallelStream().distinct().collect(Collectors.toList());
|
||||
|
||||
assertThat(listWithoutDuplicates, hasSize(3));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package com.baeldung.java8;
|
||||
|
||||
import com.baeldung.java_8_features.Vehicle;
|
||||
import com.baeldung.java_8_features.VehicleImpl;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class Java8DefaultStaticIntefaceMethodsUnitTest {
|
||||
|
||||
@Test
|
||||
public void callStaticInterfaceMethdosMethods_whenExpectedResults_thenCorrect() {
|
||||
Vehicle vehicle = new VehicleImpl();
|
||||
String overview = vehicle.getOverview();
|
||||
long[] startPosition = vehicle.startPosition();
|
||||
|
||||
assertEquals(overview, "ATV made by N&F Vehicles");
|
||||
assertEquals(startPosition[0], 23);
|
||||
assertEquals(startPosition[1], 15);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void callDefaultInterfaceMethods_whenExpectedResults_thenCorrect() {
|
||||
String producer = Vehicle.producer();
|
||||
assertEquals(producer, "N&F Vehicles");
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
package com.baeldung.java8;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.hamcrest.Matchers.anyOf;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class Java8FindAnyFindFirstUnitTest {
|
||||
|
||||
@Test
|
||||
public void createStream_whenFindAnyResultIsPresent_thenCorrect() {
|
||||
|
||||
List<String> list = Arrays.asList("A", "B", "C", "D");
|
||||
|
||||
Optional<String> result = list.stream().findAny();
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertThat(result.get(), anyOf(is("A"), is("B"), is("C"), is("D")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createParallelStream_whenFindAnyResultIsPresent_thenCorrect() throws Exception {
|
||||
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
|
||||
Optional<Integer> result = list.stream().parallel().filter(num -> num < 4).findAny();
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertThat(result.get(), anyOf(is(1), is(2), is(3)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createStream_whenFindFirstResultIsPresent_thenCorrect() {
|
||||
|
||||
List<String> list = Arrays.asList("A", "B", "C", "D");
|
||||
|
||||
Optional<String> result = list.stream().findFirst();
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertThat(result.get(), is("A"));
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
package com.baeldung.java8;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class Java8ForEachUnitTest {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(Java8ForEachUnitTest.class);
|
||||
|
||||
@Test
|
||||
public void compareForEachMethods_thenPrintResults() {
|
||||
|
||||
List<String> names = new ArrayList<>();
|
||||
names.add("Larry");
|
||||
names.add("Steve");
|
||||
names.add("James");
|
||||
names.add("Conan");
|
||||
names.add("Ellen");
|
||||
|
||||
// Java 5 - for-loop
|
||||
LOG.debug("--- Enhanced for-loop ---");
|
||||
for (String name : names) {
|
||||
LOG.debug(name);
|
||||
}
|
||||
|
||||
// Java 8 - forEach
|
||||
LOG.debug("--- forEach method ---");
|
||||
names.forEach(name -> LOG.debug(name));
|
||||
|
||||
// Anonymous inner class that implements Consumer interface
|
||||
LOG.debug("--- Anonymous inner class ---");
|
||||
names.forEach(new Consumer<String>() {
|
||||
public void accept(String name) {
|
||||
LOG.debug(name);
|
||||
}
|
||||
});
|
||||
|
||||
// Create a Consumer implementation to then use in a forEach method
|
||||
Consumer<String> consumerNames = name -> {
|
||||
LOG.debug(name);
|
||||
};
|
||||
LOG.debug("--- Implementation of Consumer interface ---");
|
||||
names.forEach(consumerNames);
|
||||
|
||||
// Print elements using a Method Reference
|
||||
LOG.debug("--- Method Reference ---");
|
||||
names.forEach(LOG::debug);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
package com.baeldung.java8;
|
||||
|
||||
import com.baeldung.Foo;
|
||||
import com.baeldung.FooExtended;
|
||||
import com.baeldung.UseFoo;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
|
||||
public class Java8FunctionalInteracesLambdasUnitTest {
|
||||
|
||||
private UseFoo useFoo;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
useFoo = new UseFoo();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void functionalInterfaceInstantiation_whenReturnDefiniteString_thenCorrect() {
|
||||
final Foo foo = parameter -> parameter + "from lambda";
|
||||
final String result = useFoo.add("Message ", foo);
|
||||
|
||||
assertEquals("Message from lambda", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void standardFIParameter_whenReturnDefiniteString_thenCorrect() {
|
||||
final Function<String, String> fn = parameter -> parameter + "from lambda";
|
||||
final String result = useFoo.addWithStandardFI("Message ", fn);
|
||||
|
||||
assertEquals("Message from lambda", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void defaultMethodFromExtendedInterface_whenReturnDefiniteString_thenCorrect() {
|
||||
final FooExtended fooExtended = string -> string;
|
||||
final String result = fooExtended.defaultMethod();
|
||||
|
||||
assertEquals("String from Bar", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void lambdaAndInnerClassInstantiation_whenReturnSameString_thenCorrect() {
|
||||
final Foo foo = parameter -> parameter + "from Foo";
|
||||
|
||||
final Foo fooByIC = new Foo() {
|
||||
@Override
|
||||
public String method(final String string) {
|
||||
return string + "from Foo";
|
||||
}
|
||||
};
|
||||
|
||||
assertEquals(foo.method("Something "), fooByIC.method("Something "));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void accessVariablesFromDifferentScopes_whenReturnPredefinedString_thenCorrect() {
|
||||
assertEquals("Results: resultIC = Inner class value, resultLambda = Enclosing scope value", useFoo.scopeExperiment());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shorteningLambdas_whenReturnEqualsResults_thenCorrect() {
|
||||
final Foo foo = parameter -> buildString(parameter);
|
||||
|
||||
final Foo fooHuge = parameter -> {
|
||||
final String result = "Something " + parameter;
|
||||
// many lines of code
|
||||
return result;
|
||||
};
|
||||
|
||||
assertEquals(foo.method("Something"), fooHuge.method("Something"));
|
||||
}
|
||||
|
||||
private String buildString(final String parameter) {
|
||||
final String result = "Something " + parameter;
|
||||
// many lines of code
|
||||
return result;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mutatingOfEffectivelyFinalVariable_whenNotEquals_thenCorrect() {
|
||||
final int[] total = new int[1];
|
||||
final Runnable r = () -> total[0]++;
|
||||
r.run();
|
||||
|
||||
assertNotEquals(0, total[0]);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,183 +0,0 @@
|
||||
package com.baeldung.java8;
|
||||
|
||||
import com.baeldung.java_8_features.groupingby.BlogPost;
|
||||
import com.baeldung.java_8_features.groupingby.BlogPostType;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
|
||||
import static java.util.Comparator.comparingInt;
|
||||
import static java.util.stream.Collectors.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class Java8GroupingByCollectorUnitTest {
|
||||
|
||||
private static final List<BlogPost> posts = Arrays.asList(new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15), new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5),
|
||||
new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20), new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35), new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15));
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByType_thenGetAMapBetweenTypeAndPosts() {
|
||||
Map<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType));
|
||||
|
||||
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
|
||||
.size());
|
||||
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
|
||||
.size());
|
||||
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
|
||||
.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeAndTheirTitlesAreJoinedInAString_thenGetAMapBetweenTypeAndCsvTitles() {
|
||||
Map<BlogPostType, String> postsPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, mapping(BlogPost::getTitle, joining(", ", "Post titles: [", "]"))));
|
||||
|
||||
assertEquals("Post titles: [News item 1, News item 2]", postsPerType.get(BlogPostType.NEWS));
|
||||
assertEquals("Post titles: [Programming guide]", postsPerType.get(BlogPostType.GUIDE));
|
||||
assertEquals("Post titles: [Tech review 1, Tech review 2]", postsPerType.get(BlogPostType.REVIEW));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeAndSumTheLikes_thenGetAMapBetweenTypeAndPostLikes() {
|
||||
Map<BlogPostType, Integer> likesPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes)));
|
||||
|
||||
assertEquals(50, likesPerType.get(BlogPostType.NEWS)
|
||||
.intValue());
|
||||
assertEquals(20, likesPerType.get(BlogPostType.REVIEW)
|
||||
.intValue());
|
||||
assertEquals(20, likesPerType.get(BlogPostType.GUIDE)
|
||||
.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeInAnEnumMap_thenGetAnEnumMapBetweenTypeAndPosts() {
|
||||
EnumMap<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList()));
|
||||
|
||||
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
|
||||
.size());
|
||||
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
|
||||
.size());
|
||||
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
|
||||
.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeInSets_thenGetAMapBetweenTypesAndSetsOfPosts() {
|
||||
Map<BlogPostType, Set<BlogPost>> postsPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, toSet()));
|
||||
|
||||
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
|
||||
.size());
|
||||
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
|
||||
.size());
|
||||
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
|
||||
.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeConcurrently_thenGetAMapBetweenTypeAndPosts() {
|
||||
ConcurrentMap<BlogPostType, List<BlogPost>> postsPerType = posts.parallelStream()
|
||||
.collect(groupingByConcurrent(BlogPost::getType));
|
||||
|
||||
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
|
||||
.size());
|
||||
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
|
||||
.size());
|
||||
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
|
||||
.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeAndAveragingLikes_thenGetAMapBetweenTypeAndAverageNumberOfLikes() {
|
||||
Map<BlogPostType, Double> averageLikesPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes)));
|
||||
|
||||
assertEquals(25, averageLikesPerType.get(BlogPostType.NEWS)
|
||||
.intValue());
|
||||
assertEquals(20, averageLikesPerType.get(BlogPostType.GUIDE)
|
||||
.intValue());
|
||||
assertEquals(10, averageLikesPerType.get(BlogPostType.REVIEW)
|
||||
.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeAndCounted_thenGetAMapBetweenTypeAndNumberOfPosts() {
|
||||
Map<BlogPostType, Long> numberOfPostsPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, counting()));
|
||||
|
||||
assertEquals(2, numberOfPostsPerType.get(BlogPostType.NEWS)
|
||||
.intValue());
|
||||
assertEquals(1, numberOfPostsPerType.get(BlogPostType.GUIDE)
|
||||
.intValue());
|
||||
assertEquals(2, numberOfPostsPerType.get(BlogPostType.REVIEW)
|
||||
.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeAndMaxingLikes_thenGetAMapBetweenTypeAndMaximumNumberOfLikes() {
|
||||
Map<BlogPostType, Optional<BlogPost>> maxLikesPerPostType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes))));
|
||||
|
||||
assertTrue(maxLikesPerPostType.get(BlogPostType.NEWS)
|
||||
.isPresent());
|
||||
assertEquals(35, maxLikesPerPostType.get(BlogPostType.NEWS)
|
||||
.get()
|
||||
.getLikes());
|
||||
|
||||
assertTrue(maxLikesPerPostType.get(BlogPostType.GUIDE)
|
||||
.isPresent());
|
||||
assertEquals(20, maxLikesPerPostType.get(BlogPostType.GUIDE)
|
||||
.get()
|
||||
.getLikes());
|
||||
|
||||
assertTrue(maxLikesPerPostType.get(BlogPostType.REVIEW)
|
||||
.isPresent());
|
||||
assertEquals(15, maxLikesPerPostType.get(BlogPostType.REVIEW)
|
||||
.get()
|
||||
.getLikes());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByAuthorAndThenByType_thenGetAMapBetweenAuthorAndMapsBetweenTypeAndBlogPosts() {
|
||||
Map<String, Map<BlogPostType, List<BlogPost>>> map = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType)));
|
||||
|
||||
assertEquals(1, map.get("Author 1")
|
||||
.get(BlogPostType.NEWS)
|
||||
.size());
|
||||
assertEquals(1, map.get("Author 1")
|
||||
.get(BlogPostType.GUIDE)
|
||||
.size());
|
||||
assertEquals(1, map.get("Author 1")
|
||||
.get(BlogPostType.REVIEW)
|
||||
.size());
|
||||
|
||||
assertEquals(1, map.get("Author 2")
|
||||
.get(BlogPostType.NEWS)
|
||||
.size());
|
||||
assertEquals(1, map.get("Author 2")
|
||||
.get(BlogPostType.REVIEW)
|
||||
.size());
|
||||
assertNull(map.get("Author 2")
|
||||
.get(BlogPostType.GUIDE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeAndSummarizingLikes_thenGetAMapBetweenTypeAndSummary() {
|
||||
Map<BlogPostType, IntSummaryStatistics> likeStatisticsPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes)));
|
||||
|
||||
IntSummaryStatistics newsLikeStatistics = likeStatisticsPerType.get(BlogPostType.NEWS);
|
||||
|
||||
assertEquals(2, newsLikeStatistics.getCount());
|
||||
assertEquals(50, newsLikeStatistics.getSum());
|
||||
assertEquals(25.0, newsLikeStatistics.getAverage(), 0.001);
|
||||
assertEquals(35, newsLikeStatistics.getMax());
|
||||
assertEquals(15, newsLikeStatistics.getMin());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
package com.baeldung.java8;
|
||||
|
||||
import com.baeldung.java_8_features.Person;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class Java8MaxMinUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenListIsOfIntegerThenMaxCanBeDoneUsingIntegerComparator() {
|
||||
//given
|
||||
final List<Integer> listOfIntegers = Arrays.asList(1, 2, 3, 4, 56, 7, 89, 10);
|
||||
final Integer expectedResult = 89;
|
||||
|
||||
//then
|
||||
final Integer max = listOfIntegers
|
||||
.stream()
|
||||
.mapToInt(v -> v)
|
||||
.max().orElseThrow(NoSuchElementException::new);
|
||||
|
||||
assertEquals("Should be 89", expectedResult, max);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenListIsOfPersonObjectThenMinCanBeDoneUsingCustomComparatorThroughLambda() {
|
||||
//given
|
||||
final Person alex = new Person("Alex", 23);
|
||||
final Person john = new Person("John", 40);
|
||||
final Person peter = new Person("Peter", 32);
|
||||
final List<Person> people = Arrays.asList(alex, john, peter);
|
||||
|
||||
//then
|
||||
final Person minByAge = people
|
||||
.stream()
|
||||
.min(Comparator.comparing(Person::getAge))
|
||||
.orElseThrow(NoSuchElementException::new);
|
||||
|
||||
assertEquals("Should be Alex", alex, minByAge);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
package com.baeldung.java8;
|
||||
|
||||
import com.baeldung.java_8_features.User;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class Java8MethodReferenceUnitTest {
|
||||
|
||||
private List<String> list;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
list = new ArrayList<>();
|
||||
list.add("One");
|
||||
list.add("OneAndOnly");
|
||||
list.add("Derek");
|
||||
list.add("Change");
|
||||
list.add("factory");
|
||||
list.add("justBefore");
|
||||
list.add("Italy");
|
||||
list.add("Italy");
|
||||
list.add("Thursday");
|
||||
list.add("");
|
||||
list.add("");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkStaticMethodReferences_whenWork_thenCorrect() {
|
||||
|
||||
List<User> users = new ArrayList<>();
|
||||
users.add(new User());
|
||||
users.add(new User());
|
||||
boolean isReal = users.stream().anyMatch(u -> User.isRealUser(u));
|
||||
boolean isRealRef = users.stream().anyMatch(User::isRealUser);
|
||||
assertTrue(isReal);
|
||||
assertTrue(isRealRef);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkInstanceMethodReferences_whenWork_thenCorrect() {
|
||||
User user = new User();
|
||||
boolean isLegalName = list.stream().anyMatch(user::isLegalName);
|
||||
assertTrue(isLegalName);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkParticularTypeReferences_whenWork_thenCorrect() {
|
||||
long count = list.stream().filter(String::isEmpty).count();
|
||||
assertEquals(count, 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkConstructorReferences_whenWork_thenCorrect() {
|
||||
Stream<User> stream = list.stream().map(User::new);
|
||||
List<User> userList = stream.collect(Collectors.toList());
|
||||
assertEquals(userList.size(), list.size());
|
||||
assertTrue(userList.get(0) instanceof User);
|
||||
}
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
package com.baeldung.java8;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.java_8_features.Address;
|
||||
import com.baeldung.java_8_features.CustomException;
|
||||
import com.baeldung.java_8_features.OptionalAddress;
|
||||
import com.baeldung.java_8_features.OptionalUser;
|
||||
import com.baeldung.java_8_features.User;
|
||||
|
||||
public class Java8OptionalUnitTest {
|
||||
|
||||
private List<String> list;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
list = new ArrayList<>();
|
||||
list.add("One");
|
||||
list.add("OneAndOnly");
|
||||
list.add("Derek");
|
||||
list.add("Change");
|
||||
list.add("factory");
|
||||
list.add("justBefore");
|
||||
list.add("Italy");
|
||||
list.add("Italy");
|
||||
list.add("Thursday");
|
||||
list.add("");
|
||||
list.add("");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkOptional_whenAsExpected_thenCorrect() {
|
||||
Optional<String> optionalEmpty = Optional.empty();
|
||||
assertFalse(optionalEmpty.isPresent());
|
||||
|
||||
String str = "value";
|
||||
Optional<String> optional = Optional.of(str);
|
||||
assertEquals(optional.get(), "value");
|
||||
|
||||
Optional<String> optionalNullable = Optional.ofNullable(str);
|
||||
Optional<String> optionalNull = Optional.ofNullable(null);
|
||||
assertEquals(optionalNullable.get(), "value");
|
||||
assertFalse(optionalNull.isPresent());
|
||||
|
||||
List<String> listOpt = Optional.of(list).orElse(new ArrayList<>());
|
||||
List<String> listNull = null;
|
||||
List<String> listOptNull = Optional.ofNullable(listNull).orElse(new ArrayList<>());
|
||||
assertTrue(listOpt == list);
|
||||
assertTrue(listOptNull.isEmpty());
|
||||
|
||||
Optional<User> user = Optional.ofNullable(getUser());
|
||||
String result = user.map(User::getAddress).map(Address::getStreet).orElse("not specified");
|
||||
assertEquals(result, "1st Avenue");
|
||||
|
||||
Optional<OptionalUser> optionalUser = Optional.ofNullable(getOptionalUser());
|
||||
String resultOpt = optionalUser.flatMap(OptionalUser::getAddress).flatMap(OptionalAddress::getStreet).orElse("not specified");
|
||||
assertEquals(resultOpt, "1st Avenue");
|
||||
|
||||
Optional<User> userNull = Optional.ofNullable(getUserNull());
|
||||
String resultNull = userNull.map(User::getAddress).map(Address::getStreet).orElse("not specified");
|
||||
assertEquals(resultNull, "not specified");
|
||||
|
||||
Optional<OptionalUser> optionalUserNull = Optional.ofNullable(getOptionalUserNull());
|
||||
String resultOptNull = optionalUserNull.flatMap(OptionalUser::getAddress).flatMap(OptionalAddress::getStreet).orElse("not specified");
|
||||
assertEquals(resultOptNull, "not specified");
|
||||
|
||||
}
|
||||
|
||||
@Test(expected = CustomException.class)
|
||||
public void callMethod_whenCustomException_thenCorrect() {
|
||||
User user = new User();
|
||||
String result = user.getOrThrow();
|
||||
}
|
||||
|
||||
private User getUser() {
|
||||
User user = new User();
|
||||
Address address = new Address();
|
||||
address.setStreet("1st Avenue");
|
||||
user.setAddress(address);
|
||||
return user;
|
||||
}
|
||||
|
||||
private OptionalUser getOptionalUser() {
|
||||
OptionalUser user = new OptionalUser();
|
||||
OptionalAddress address = new OptionalAddress();
|
||||
address.setStreet("1st Avenue");
|
||||
user.setAddress(address);
|
||||
return user;
|
||||
}
|
||||
|
||||
private OptionalUser getOptionalUserNull() {
|
||||
OptionalUser user = new OptionalUser();
|
||||
OptionalAddress address = new OptionalAddress();
|
||||
address.setStreet(null);
|
||||
user.setAddress(address);
|
||||
return user;
|
||||
}
|
||||
|
||||
private User getUserNull() {
|
||||
User user = new User();
|
||||
Address address = new Address();
|
||||
address.setStreet(null);
|
||||
user.setAddress(address);
|
||||
return user;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
package com.baeldung.java8;
|
||||
|
||||
import com.baeldung.java8.entity.Human;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.primitives.Ints;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
public class Java8SortUnitTest {
|
||||
|
||||
// tests -
|
||||
|
||||
@Test
|
||||
public final void givenPreLambda_whenSortingEntitiesByName_thenCorrectlySorted() {
|
||||
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
|
||||
|
||||
Collections.sort(humans, new Comparator<Human>() {
|
||||
@Override
|
||||
public final int compare(final Human h1, final Human h2) {
|
||||
return h1.getName().compareTo(h2.getName());
|
||||
}
|
||||
});
|
||||
|
||||
Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenSortingEntitiesByName_thenCorrectlySorted() {
|
||||
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
|
||||
|
||||
humans.sort((final Human h1, final Human h2) -> h1.getName().compareTo(h2.getName()));
|
||||
|
||||
Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenLambdaShortForm_whenSortingEntitiesByName_thenCorrectlySorted() {
|
||||
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
|
||||
|
||||
humans.sort((h1, h2) -> h1.getName().compareTo(h2.getName()));
|
||||
|
||||
Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenSortingEntitiesByNameThenAge_thenCorrectlySorted() {
|
||||
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 12), new Human("Sarah", 10), new Human("Zack", 12));
|
||||
humans.sort((lhs, rhs) -> {
|
||||
if (lhs.getName().equals(rhs.getName())) {
|
||||
return lhs.getAge() - rhs.getAge();
|
||||
} else {
|
||||
return lhs.getName().compareTo(rhs.getName());
|
||||
}
|
||||
});
|
||||
Assert.assertThat(humans.get(0), equalTo(new Human("Sarah", 10)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenCompositionVerbose_whenSortingEntitiesByNameThenAge_thenCorrectlySorted() {
|
||||
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 12), new Human("Sarah", 10), new Human("Zack", 12));
|
||||
final Comparator<Human> byName = (h1, h2) -> h1.getName().compareTo(h2.getName());
|
||||
final Comparator<Human> byAge = (h1, h2) -> Ints.compare(h1.getAge(), h2.getAge());
|
||||
|
||||
humans.sort(byName.thenComparing(byAge));
|
||||
Assert.assertThat(humans.get(0), equalTo(new Human("Sarah", 10)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenComposition_whenSortingEntitiesByNameThenAge_thenCorrectlySorted() {
|
||||
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 12), new Human("Sarah", 10), new Human("Zack", 12));
|
||||
|
||||
humans.sort(Comparator.comparing(Human::getName).thenComparing(Human::getAge));
|
||||
Assert.assertThat(humans.get(0), equalTo(new Human("Sarah", 10)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenSortingEntitiesByAge_thenCorrectlySorted() {
|
||||
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
|
||||
|
||||
humans.sort((h1, h2) -> Ints.compare(h1.getAge(), h2.getAge()));
|
||||
Assert.assertThat(humans.get(0), equalTo(new Human("Sarah", 10)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenSortingEntitiesByNameReversed_thenCorrectlySorted() {
|
||||
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
|
||||
final Comparator<Human> comparator = (h1, h2) -> h1.getName().compareTo(h2.getName());
|
||||
|
||||
humans.sort(comparator.reversed());
|
||||
Assert.assertThat(humans.get(0), equalTo(new Human("Sarah", 10)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenMethodDefinition_whenSortingEntitiesByNameThenAge_thenCorrectlySorted() {
|
||||
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
|
||||
|
||||
humans.sort(Human::compareByNameThenAge);
|
||||
Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenInstanceMethod_whenSortingEntitiesByName_thenCorrectlySorted() {
|
||||
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
|
||||
|
||||
humans.sort(Comparator.comparing(Human::getName));
|
||||
Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,243 +0,0 @@
|
||||
package com.baeldung.java8;
|
||||
|
||||
import com.baeldung.streamApi.Product;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.*;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class Java8StreamApiUnitTest {
|
||||
|
||||
private long counter;
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(Java8StreamApiUnitTest.class);
|
||||
|
||||
private List<Product> productList;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
productList = Arrays.asList(new Product(23, "potatoes"), new Product(14, "orange"), new Product(13, "lemon"), new Product(23, "bread"), new Product(13, "sugar"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkPipeline_whenStreamOneElementShorter_thenCorrect() {
|
||||
|
||||
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
|
||||
long size = list.stream().skip(1).map(element -> element.substring(0, 3)).count();
|
||||
assertEquals(list.size() - 1, size);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkOrder_whenChangeQuantityOfMethodCalls_thenCorrect() {
|
||||
|
||||
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
|
||||
|
||||
counter = 0;
|
||||
long sizeFirst = list.stream().skip(2).map(element -> {
|
||||
wasCalled();
|
||||
return element.substring(0, 3);
|
||||
}).count();
|
||||
assertEquals(1, counter);
|
||||
|
||||
counter = 0;
|
||||
long sizeSecond = list.stream().map(element -> {
|
||||
wasCalled();
|
||||
return element.substring(0, 3);
|
||||
}).skip(2).count();
|
||||
assertEquals(3, counter);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createEmptyStream_whenEmpty_thenCorrect() {
|
||||
|
||||
Stream<String> streamEmpty = Stream.empty();
|
||||
assertEquals(0, streamEmpty.count());
|
||||
|
||||
List<String> names = Collections.emptyList();
|
||||
Stream<String> streamOf = Product.streamOf(names);
|
||||
assertTrue(streamOf.count() == 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createStream_whenCreated_thenCorrect() {
|
||||
|
||||
Collection<String> collection = Arrays.asList("a", "b", "c");
|
||||
Stream<String> streamOfCollection = collection.stream();
|
||||
assertEquals(3, streamOfCollection.count());
|
||||
|
||||
Stream<String> streamOfArray = Stream.of("a", "b", "c");
|
||||
assertEquals(3, streamOfArray.count());
|
||||
|
||||
String[] arr = new String[] { "a", "b", "c" };
|
||||
Stream<String> streamOfArrayPart = Arrays.stream(arr, 1, 3);
|
||||
assertEquals(2, streamOfArrayPart.count());
|
||||
|
||||
IntStream intStream = IntStream.range(1, 3);
|
||||
LongStream longStream = LongStream.rangeClosed(1, 3);
|
||||
Random random = new Random();
|
||||
DoubleStream doubleStream = random.doubles(3);
|
||||
assertEquals(2, intStream.count());
|
||||
assertEquals(3, longStream.count());
|
||||
assertEquals(3, doubleStream.count());
|
||||
|
||||
IntStream streamOfChars = "abc".chars();
|
||||
IntStream str = "".chars();
|
||||
assertEquals(3, streamOfChars.count());
|
||||
|
||||
Stream<String> streamOfString = Pattern.compile(", ").splitAsStream("a, b, c");
|
||||
assertEquals("a", streamOfString.findFirst().get());
|
||||
|
||||
Path path = getPath();
|
||||
Stream<String> streamOfStrings = null;
|
||||
try {
|
||||
streamOfStrings = Files.lines(path, Charset.forName("UTF-8"));
|
||||
} catch (IOException e) {
|
||||
log.error("Error creating streams from paths {}", path, e.getMessage(), e);
|
||||
}
|
||||
assertEquals("a", streamOfStrings.findFirst().get());
|
||||
|
||||
Stream<String> streamBuilder = Stream.<String> builder().add("a").add("b").add("c").build();
|
||||
assertEquals(3, streamBuilder.count());
|
||||
|
||||
Stream<String> streamGenerated = Stream.generate(() -> "element").limit(10);
|
||||
assertEquals(10, streamGenerated.count());
|
||||
|
||||
Stream<Integer> streamIterated = Stream.iterate(40, n -> n + 2).limit(20);
|
||||
assertTrue(40 <= streamIterated.findAny().get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void runStreamPipeline_whenOrderIsRight_thenCorrect() {
|
||||
|
||||
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
|
||||
Optional<String> stream = list.stream().filter(element -> {
|
||||
log.info("filter() was called");
|
||||
return element.contains("2");
|
||||
}).map(element -> {
|
||||
log.info("map() was called");
|
||||
return element.toUpperCase();
|
||||
}).findFirst();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void reduce_whenExpected_thenCorrect() {
|
||||
|
||||
OptionalInt reduced = IntStream.range(1, 4).reduce((a, b) -> a + b);
|
||||
assertEquals(6, reduced.getAsInt());
|
||||
|
||||
int reducedTwoParams = IntStream.range(1, 4).reduce(10, (a, b) -> a + b);
|
||||
assertEquals(16, reducedTwoParams);
|
||||
|
||||
int reducedThreeParams = Stream.of(1, 2, 3).reduce(10, (a, b) -> a + b, (a, b) -> {
|
||||
log.info("combiner was called");
|
||||
return a + b;
|
||||
});
|
||||
assertEquals(16, reducedThreeParams);
|
||||
|
||||
int reducedThreeParamsParallel = Arrays.asList(1, 2, 3).parallelStream().reduce(10, (a, b) -> a + b, (a, b) -> {
|
||||
log.info("combiner was called");
|
||||
return a + b;
|
||||
});
|
||||
assertEquals(36, reducedThreeParamsParallel);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void collecting_whenAsExpected_thenCorrect() {
|
||||
|
||||
List<String> collectorCollection = productList.stream().map(Product::getName).collect(Collectors.toList());
|
||||
|
||||
assertTrue(collectorCollection instanceof List);
|
||||
assertEquals(5, collectorCollection.size());
|
||||
|
||||
String listToString = productList.stream().map(Product::getName).collect(Collectors.joining(", ", "[", "]"));
|
||||
|
||||
assertTrue(listToString.contains(",") && listToString.contains("[") && listToString.contains("]"));
|
||||
|
||||
double averagePrice = productList.stream().collect(Collectors.averagingInt(Product::getPrice));
|
||||
assertTrue(17.2 == averagePrice);
|
||||
|
||||
int summingPrice = productList.stream().collect(Collectors.summingInt(Product::getPrice));
|
||||
assertEquals(86, summingPrice);
|
||||
|
||||
IntSummaryStatistics statistics = productList.stream().collect(Collectors.summarizingInt(Product::getPrice));
|
||||
assertEquals(23, statistics.getMax());
|
||||
|
||||
Map<Integer, List<Product>> collectorMapOfLists = productList.stream().collect(Collectors.groupingBy(Product::getPrice));
|
||||
assertEquals(3, collectorMapOfLists.keySet().size());
|
||||
|
||||
Map<Boolean, List<Product>> mapPartioned = productList.stream().collect(Collectors.partitioningBy(element -> element.getPrice() > 15));
|
||||
assertEquals(2, mapPartioned.keySet().size());
|
||||
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void collect_whenThrows_thenCorrect() {
|
||||
Set<Product> unmodifiableSet = productList.stream().collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet));
|
||||
unmodifiableSet.add(new Product(4, "tea"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void customCollector_whenResultContainsAllElementsFrSource_thenCorrect() {
|
||||
Collector<Product, ?, LinkedList<Product>> toLinkedList = Collector.of(LinkedList::new, LinkedList::add, (first, second) -> {
|
||||
first.addAll(second);
|
||||
return first;
|
||||
});
|
||||
|
||||
LinkedList<Product> linkedListOfPersons = productList.stream().collect(toLinkedList);
|
||||
assertTrue(linkedListOfPersons.containsAll(productList));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parallelStream_whenWorks_thenCorrect() {
|
||||
Stream<Product> streamOfCollection = productList.parallelStream();
|
||||
boolean isParallel = streamOfCollection.isParallel();
|
||||
boolean haveBigPrice = streamOfCollection.map(product -> product.getPrice() * 12).anyMatch(price -> price > 200);
|
||||
assertTrue(isParallel && haveBigPrice);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parallel_whenIsParallel_thenCorrect() {
|
||||
IntStream intStreamParallel = IntStream.range(1, 150).parallel().map(element -> element * 34);
|
||||
boolean isParallel = intStreamParallel.isParallel();
|
||||
assertTrue(isParallel);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parallel_whenIsSequential_thenCorrect() {
|
||||
IntStream intStreamParallel = IntStream.range(1, 150).parallel().map(element -> element * 34);
|
||||
IntStream intStreamSequential = intStreamParallel.sequential();
|
||||
boolean isParallel = intStreamParallel.isParallel();
|
||||
assertFalse(isParallel);
|
||||
}
|
||||
|
||||
private Path getPath() {
|
||||
Path path = null;
|
||||
try {
|
||||
path = Files.createTempFile(null, ".txt");
|
||||
} catch (IOException e) {
|
||||
log.error(e.getMessage());
|
||||
}
|
||||
|
||||
try (BufferedWriter writer = Files.newBufferedWriter(path)) {
|
||||
writer.write("a\nb\nc");
|
||||
} catch (IOException e) {
|
||||
log.error(e.getMessage());
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
private void wasCalled() {
|
||||
counter++;
|
||||
}
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
package com.baeldung.java8;
|
||||
|
||||
import com.baeldung.java_8_features.Detail;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class Java8StreamsUnitTest {
|
||||
|
||||
private List<String> list;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
list = new ArrayList<>();
|
||||
list.add("One");
|
||||
list.add("OneAndOnly");
|
||||
list.add("Derek");
|
||||
list.add("Change");
|
||||
list.add("factory");
|
||||
list.add("justBefore");
|
||||
list.add("Italy");
|
||||
list.add("Italy");
|
||||
list.add("Thursday");
|
||||
list.add("");
|
||||
list.add("");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkStreamCount_whenCreating_givenDifferentSources() {
|
||||
String[] arr = new String[] { "a", "b", "c" };
|
||||
Stream<String> streamArr = Arrays.stream(arr);
|
||||
assertEquals(streamArr.count(), 3);
|
||||
|
||||
Stream<String> streamOf = Stream.of("a", "b", "c");
|
||||
assertEquals(streamOf.count(), 3);
|
||||
|
||||
long count = list.stream().distinct().count();
|
||||
assertEquals(count, 9);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkStreamCount_whenOperationFilter_thanCorrect() {
|
||||
Stream<String> streamFilter = list.stream().filter(element -> element.isEmpty());
|
||||
assertEquals(streamFilter.count(), 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkStreamCount_whenOperationMap_thanCorrect() {
|
||||
List<String> uris = new ArrayList<>();
|
||||
uris.add("C:\\My.txt");
|
||||
Stream<Path> streamMap = uris.stream().map(uri -> Paths.get(uri));
|
||||
assertEquals(streamMap.count(), 1);
|
||||
|
||||
List<Detail> details = new ArrayList<>();
|
||||
details.add(new Detail());
|
||||
details.add(new Detail());
|
||||
Stream<String> streamFlatMap = details.stream().flatMap(detail -> detail.getParts().stream());
|
||||
assertEquals(streamFlatMap.count(), 4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkStreamCount_whenOperationMatch_thenCorrect() {
|
||||
boolean isValid = list.stream().anyMatch(element -> element.contains("h"));
|
||||
boolean isValidOne = list.stream().allMatch(element -> element.contains("h"));
|
||||
boolean isValidTwo = list.stream().noneMatch(element -> element.contains("h"));
|
||||
assertTrue(isValid);
|
||||
assertFalse(isValidOne);
|
||||
assertFalse(isValidTwo);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkStreamReducedValue_whenOperationReduce_thenCorrect() {
|
||||
List<Integer> integers = new ArrayList<>();
|
||||
integers.add(1);
|
||||
integers.add(1);
|
||||
integers.add(1);
|
||||
Integer reduced = integers.stream().reduce(23, (a, b) -> a + b);
|
||||
assertTrue(reduced == 26);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkStreamContains_whenOperationCollect_thenCorrect() {
|
||||
List<String> resultList = list.stream().map(element -> element.toUpperCase()).collect(Collectors.toList());
|
||||
assertEquals(resultList.size(), list.size());
|
||||
assertTrue(resultList.contains(""));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkParallelStream_whenDoWork() {
|
||||
list.parallelStream().forEach(element -> doWork(element));
|
||||
}
|
||||
|
||||
private void doWork(String string) {
|
||||
assertTrue(true); // just imitate an amount of work
|
||||
}
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
package com.baeldung.java8;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.util.Date;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class JavaTryWithResourcesLongRunningUnitTest {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(JavaTryWithResourcesLongRunningUnitTest.class);
|
||||
|
||||
|
||||
private static final String TEST_STRING_HELLO_WORLD = "Hello World";
|
||||
private Date resource1Date, resource2Date;
|
||||
|
||||
// tests
|
||||
|
||||
/* Example for using Try_with_resources */
|
||||
@Test
|
||||
public void whenWritingToStringWriter_thenCorrectlyWritten() {
|
||||
final StringWriter sw = new StringWriter();
|
||||
try (PrintWriter pw = new PrintWriter(sw, true)) {
|
||||
pw.print(TEST_STRING_HELLO_WORLD);
|
||||
}
|
||||
|
||||
Assert.assertEquals(sw.getBuffer().toString(), TEST_STRING_HELLO_WORLD);
|
||||
}
|
||||
|
||||
/* Example for using multiple resources */
|
||||
@Test
|
||||
public void givenStringToScanner_whenWritingToStringWriter_thenCorrectlyWritten() {
|
||||
|
||||
final StringWriter sw = new StringWriter();
|
||||
try (Scanner sc = new Scanner(TEST_STRING_HELLO_WORLD); PrintWriter pw = new PrintWriter(sw, true)) {
|
||||
while (sc.hasNext()) {
|
||||
pw.print(sc.nextLine());
|
||||
}
|
||||
}
|
||||
|
||||
Assert.assertEquals(sw.getBuffer().toString(), TEST_STRING_HELLO_WORLD);
|
||||
}
|
||||
|
||||
/* Example to show order in which the resources are closed */
|
||||
@Test
|
||||
public void whenFirstAutoClosableResourceIsinitializedFirst_thenFirstAutoClosableResourceIsReleasedFirst() throws Exception {
|
||||
try (AutoCloseableResourcesFirst af = new AutoCloseableResourcesFirst(); AutoCloseableResourcesSecond as = new AutoCloseableResourcesSecond()) {
|
||||
af.doSomething();
|
||||
as.doSomething();
|
||||
}
|
||||
Assert.assertTrue(resource1Date.after(resource2Date));
|
||||
}
|
||||
|
||||
class AutoCloseableResourcesFirst implements AutoCloseable {
|
||||
public AutoCloseableResourcesFirst() {
|
||||
LOG.debug("Constructor -> AutoCloseableResources_First");
|
||||
}
|
||||
|
||||
public void doSomething() {
|
||||
LOG.debug("Something -> AutoCloseableResources_First");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws Exception {
|
||||
LOG.debug("Closed AutoCloseableResources_First");
|
||||
resource1Date = new Date();
|
||||
}
|
||||
}
|
||||
|
||||
class AutoCloseableResourcesSecond implements AutoCloseable {
|
||||
public AutoCloseableResourcesSecond() {
|
||||
LOG.debug("Constructor -> AutoCloseableResources_Second");
|
||||
}
|
||||
|
||||
public void doSomething() {
|
||||
LOG.debug("Something -> AutoCloseableResources_Second");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws Exception {
|
||||
LOG.debug("Closed AutoCloseableResources_Second");
|
||||
resource2Date = new Date();
|
||||
Thread.sleep(10000);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
package com.baeldung.java8.base64;
|
||||
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class ApacheCommonsEncodeDecodeUnitTest {
|
||||
|
||||
// tests
|
||||
|
||||
@Test
|
||||
public void whenStringIsEncoded() throws UnsupportedEncodingException {
|
||||
final String originalInput = "test input";
|
||||
final Base64 base64 = new Base64();
|
||||
final String encodedString = new String(base64.encode(originalInput.getBytes()));
|
||||
|
||||
assertNotNull(encodedString);
|
||||
assertNotEquals(originalInput, encodedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringIsEncoded_thenStringCanBeDecoded() throws UnsupportedEncodingException {
|
||||
final String originalInput = "test input";
|
||||
final Base64 base64 = new Base64();
|
||||
final String encodedString = new String(base64.encode(originalInput.getBytes()));
|
||||
|
||||
final String decodedString = new String(base64.decode(encodedString.getBytes()));
|
||||
|
||||
assertNotNull(decodedString);
|
||||
assertEquals(originalInput, decodedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringIsEncodedUsingStaticMethod() throws UnsupportedEncodingException {
|
||||
final String originalInput = "test input";
|
||||
final String encodedString = new String(Base64.encodeBase64(originalInput.getBytes()));
|
||||
|
||||
assertNotNull(encodedString);
|
||||
assertNotEquals(originalInput, encodedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringIsEncodedUsingStaticMethod_thenStringCanBeDecodedUsingStaticMethod() throws UnsupportedEncodingException {
|
||||
final String originalInput = "test input";
|
||||
final String encodedString = new String(Base64.encodeBase64(originalInput.getBytes()));
|
||||
|
||||
final String decodedString = new String(Base64.decodeBase64(encodedString.getBytes()));
|
||||
|
||||
assertNotNull(decodedString);
|
||||
assertEquals(originalInput, decodedString);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
package com.baeldung.java8.base64;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.Base64;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class Java8EncodeDecodeUnitTest {
|
||||
|
||||
// tests
|
||||
|
||||
@Test
|
||||
public void whenStringIsEncoded_thenOk() throws UnsupportedEncodingException {
|
||||
final String originalInput = "test input";
|
||||
final String encodedString = Base64.getEncoder().encodeToString(originalInput.getBytes());
|
||||
|
||||
assertNotNull(encodedString);
|
||||
assertNotEquals(originalInput, encodedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringIsEncoded_thenStringCanBeDecoded() throws UnsupportedEncodingException {
|
||||
final String originalInput = "test input";
|
||||
final String encodedString = Base64.getEncoder().encodeToString(originalInput.getBytes());
|
||||
|
||||
final byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
|
||||
final String decodedString = new String(decodedBytes);
|
||||
|
||||
assertNotNull(decodedString);
|
||||
assertEquals(originalInput, decodedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringIsEncodedWithoutPadding_thenOk() throws UnsupportedEncodingException {
|
||||
final String originalInput = "test input";
|
||||
final String encodedString = Base64.getEncoder().withoutPadding().encodeToString(originalInput.getBytes());
|
||||
|
||||
assertNotNull(encodedString);
|
||||
assertNotEquals(originalInput, encodedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringIsEncodedWithoutPadding_thenStringCanBeDecoded() throws UnsupportedEncodingException {
|
||||
final String originalInput = "test input";
|
||||
final String encodedString = Base64.getEncoder().withoutPadding().encodeToString(originalInput.getBytes());
|
||||
|
||||
final byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
|
||||
final String decodedString = new String(decodedBytes);
|
||||
|
||||
assertNotNull(decodedString);
|
||||
assertEquals(originalInput, decodedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUrlIsEncoded_thenOk() throws UnsupportedEncodingException {
|
||||
final String originalUrl = "https://www.google.co.nz/?gfe_rd=cr&ei=dzbFVf&gws_rd=ssl#q=java";
|
||||
final String encodedUrl = Base64.getUrlEncoder().encodeToString(originalUrl.getBytes());
|
||||
assertNotNull(encodedUrl);
|
||||
assertNotEquals(originalUrl, encodedUrl);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUrlIsEncoded_thenURLCanBeDecoded() throws UnsupportedEncodingException {
|
||||
final String originalUrl = "https://www.google.co.nz/?gfe_rd=cr&ei=dzbFVf&gws_rd=ssl#q=java";
|
||||
final String encodedUrl = Base64.getUrlEncoder().encodeToString(originalUrl.getBytes());
|
||||
|
||||
final byte[] decodedBytes = Base64.getUrlDecoder().decode(encodedUrl.getBytes());
|
||||
final String decodedUrl = new String(decodedBytes);
|
||||
|
||||
assertNotNull(decodedUrl);
|
||||
assertEquals(originalUrl, decodedUrl);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMimeIsEncoded_thenOk() throws UnsupportedEncodingException {
|
||||
final StringBuilder buffer = getMimeBuffer();
|
||||
|
||||
final byte[] forEncode = buffer.toString().getBytes();
|
||||
final String encodedMime = Base64.getMimeEncoder().encodeToString(forEncode);
|
||||
|
||||
assertNotNull(encodedMime);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMimeIsEncoded_thenItCanBeDecoded() throws UnsupportedEncodingException {
|
||||
final StringBuilder buffer = getMimeBuffer();
|
||||
|
||||
final byte[] forEncode = buffer.toString().getBytes();
|
||||
final String encodedMime = Base64.getMimeEncoder().encodeToString(forEncode);
|
||||
|
||||
final byte[] decodedBytes = Base64.getMimeDecoder().decode(encodedMime);
|
||||
final String decodedMime = new String(decodedBytes);
|
||||
assertNotNull(decodedMime);
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
private static StringBuilder getMimeBuffer() {
|
||||
final StringBuilder buffer = new StringBuilder();
|
||||
for (int count = 0; count < 10; ++count) {
|
||||
buffer.append(UUID.randomUUID().toString());
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package com.baeldung.java8.comparator;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.ToString;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@ToString
|
||||
@EqualsAndHashCode
|
||||
public class Employee implements Comparable<Employee>{
|
||||
String name;
|
||||
int age;
|
||||
double salary;
|
||||
long mobile;
|
||||
|
||||
@Override
|
||||
public int compareTo(Employee argEmployee) {
|
||||
return name.compareTo(argEmployee.getName());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,155 +0,0 @@
|
||||
package com.baeldung.java8.comparator;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import lombok.Data;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class Java8ComparatorUnitTest {
|
||||
|
||||
private Employee[] employees;
|
||||
private Employee[] employeesArrayWithNulls;
|
||||
private Employee[] sortedEmployeesByName;
|
||||
private Employee[] sortedEmployeesByNameDesc;
|
||||
private Employee[] sortedEmployeesByAge;
|
||||
private Employee[] sortedEmployeesByMobile;
|
||||
private Employee[] sortedEmployeesBySalary;
|
||||
private Employee[] sortedEmployeesArray_WithNullsFirst;
|
||||
private Employee[] sortedEmployeesArray_WithNullsLast;
|
||||
private Employee[] sortedEmployeesByNameAge;
|
||||
private Employee[] someMoreEmployees;
|
||||
private Employee[] sortedEmployeesByAgeName;;
|
||||
|
||||
@Before
|
||||
public void initData() {
|
||||
employees = new Employee[] { new Employee("John", 25, 3000, 9922001), new Employee("Ace", 22, 2000, 5924001), new Employee("Keith", 35, 4000, 3924401) };
|
||||
employeesArrayWithNulls = new Employee[] { new Employee("John", 25, 3000, 9922001), null, new Employee("Ace", 22, 2000, 5924001), null, new Employee("Keith", 35, 4000, 3924401) };
|
||||
|
||||
sortedEmployeesByName = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
|
||||
sortedEmployeesByNameDesc = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("John", 25, 3000, 9922001), new Employee("Ace", 22, 2000, 5924001) };
|
||||
|
||||
sortedEmployeesByAge = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
|
||||
|
||||
sortedEmployeesByMobile = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), };
|
||||
|
||||
sortedEmployeesBySalary = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401), };
|
||||
|
||||
sortedEmployeesArray_WithNullsFirst = new Employee[] { null, null, new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
|
||||
sortedEmployeesArray_WithNullsLast = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401), null, null };
|
||||
|
||||
someMoreEmployees = new Employee[] { new Employee("Jake", 25, 3000, 9922001), new Employee("Jake", 22, 2000, 5924001), new Employee("Ace", 22, 3000, 6423001), new Employee("Keith", 35, 4000, 3924401) };
|
||||
|
||||
sortedEmployeesByAgeName = new Employee[] { new Employee("Ace", 22, 3000, 6423001), new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
|
||||
sortedEmployeesByNameAge = new Employee[] { new Employee("Ace", 22, 3000, 6423001), new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenComparing_thenSortedByName() {
|
||||
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
|
||||
Arrays.sort(employees, employeeNameComparator);
|
||||
// System.out.println(Arrays.toString(employees));
|
||||
assertTrue(Arrays.equals(employees, sortedEmployeesByName));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenComparingWithComparator_thenSortedByNameDesc() {
|
||||
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName, (s1, s2) -> {
|
||||
return s2.compareTo(s1);
|
||||
});
|
||||
Arrays.sort(employees, employeeNameComparator);
|
||||
// System.out.println(Arrays.toString(employees));
|
||||
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReversed_thenSortedByNameDesc() {
|
||||
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
|
||||
Comparator<Employee> employeeNameComparatorReversed = employeeNameComparator.reversed();
|
||||
Arrays.sort(employees, employeeNameComparatorReversed);
|
||||
// System.out.println(Arrays.toString(employees));
|
||||
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenComparingInt_thenSortedByAge() {
|
||||
Comparator<Employee> employeeAgeComparator = Comparator.comparingInt(Employee::getAge);
|
||||
Arrays.sort(employees, employeeAgeComparator);
|
||||
// System.out.println(Arrays.toString(employees));
|
||||
assertTrue(Arrays.equals(employees, sortedEmployeesByAge));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenComparingLong_thenSortedByMobile() {
|
||||
Comparator<Employee> employeeMobileComparator = Comparator.comparingLong(Employee::getMobile);
|
||||
Arrays.sort(employees, employeeMobileComparator);
|
||||
// System.out.println(Arrays.toString(employees));
|
||||
assertTrue(Arrays.equals(employees, sortedEmployeesByMobile));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenComparingDouble_thenSortedBySalary() {
|
||||
Comparator<Employee> employeeSalaryComparator = Comparator.comparingDouble(Employee::getSalary);
|
||||
Arrays.sort(employees, employeeSalaryComparator);
|
||||
// System.out.println(Arrays.toString(employees));
|
||||
assertTrue(Arrays.equals(employees, sortedEmployeesBySalary));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNaturalOrder_thenSortedByName() {
|
||||
Comparator<Employee> employeeNameComparator = Comparator.<Employee> naturalOrder();
|
||||
Arrays.sort(employees, employeeNameComparator);
|
||||
// System.out.println(Arrays.toString(employees));
|
||||
assertTrue(Arrays.equals(employees, sortedEmployeesByName));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReverseOrder_thenSortedByNameDesc() {
|
||||
Comparator<Employee> employeeNameComparator = Comparator.<Employee> reverseOrder();
|
||||
Arrays.sort(employees, employeeNameComparator);
|
||||
// System.out.println(Arrays.toString(employees));
|
||||
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNullsFirst_thenSortedByNameWithNullsFirst() {
|
||||
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
|
||||
Comparator<Employee> employeeNameComparator_nullFirst = Comparator.nullsFirst(employeeNameComparator);
|
||||
Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullFirst);
|
||||
// System.out.println(Arrays.toString(employeesArrayWithNulls));
|
||||
assertTrue(Arrays.equals(employeesArrayWithNulls, sortedEmployeesArray_WithNullsFirst));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNullsLast_thenSortedByNameWithNullsLast() {
|
||||
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
|
||||
Comparator<Employee> employeeNameComparator_nullLast = Comparator.nullsLast(employeeNameComparator);
|
||||
Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullLast);
|
||||
// System.out.println(Arrays.toString(employeesArrayWithNulls));
|
||||
assertTrue(Arrays.equals(employeesArrayWithNulls, sortedEmployeesArray_WithNullsLast));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenThenComparing_thenSortedByAgeName() {
|
||||
Comparator<Employee> employee_Age_Name_Comparator = Comparator.comparing(Employee::getAge)
|
||||
.thenComparing(Employee::getName);
|
||||
|
||||
Arrays.sort(someMoreEmployees, employee_Age_Name_Comparator);
|
||||
// System.out.println(Arrays.toString(someMoreEmployees));
|
||||
assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByAgeName));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenThenComparing_thenSortedByNameAge() {
|
||||
Comparator<Employee> employee_Name_Age_Comparator = Comparator.comparing(Employee::getName)
|
||||
.thenComparingInt(Employee::getAge);
|
||||
|
||||
Arrays.sort(someMoreEmployees, employee_Name_Age_Comparator);
|
||||
// System.out.println(Arrays.toString(someMoreEmployees));
|
||||
assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByNameAge));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
package com.baeldung.java8.entity;
|
||||
|
||||
public class Human {
|
||||
private String name;
|
||||
private int age;
|
||||
|
||||
public Human() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Human(final String name, final int age) {
|
||||
super();
|
||||
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(final int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
// compare
|
||||
|
||||
public static int compareByNameThenAge(final Human lhs, final Human rhs) {
|
||||
if (lhs.name.equals(rhs.name)) {
|
||||
return lhs.age - rhs.age;
|
||||
} else {
|
||||
return lhs.name.compareTo(rhs.name);
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + age;
|
||||
result = prime * result + ((name == null) ? 0 : name.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
if (getClass() != obj.getClass()) {
|
||||
return false;
|
||||
}
|
||||
final Human other = (Human) obj;
|
||||
if (age != other.age) {
|
||||
return false;
|
||||
}
|
||||
if (name == null) {
|
||||
if (other.name != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (!name.equals(other.name)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
builder.append("Human [name=").append(name).append(", age=").append(age).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
package com.baeldung.java8.lambda.exceptions;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static com.baeldung.java8.lambda.exceptions.LambdaExceptionWrappers.*;
|
||||
|
||||
public class LambdaExceptionWrappersUnitTest {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(LambdaExceptionWrappersUnitTest.class);
|
||||
|
||||
private List<Integer> integers;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
integers = Arrays.asList(3, 9, 7, 0, 10, 20);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNoExceptionFromLambdaWrapper_thenSuccess() {
|
||||
integers.forEach(lambdaWrapper(i -> LOG.debug("{}", 50 / i)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNoExceptionFromConsumerWrapper_thenSuccess() {
|
||||
integers.forEach(consumerWrapper(i -> LOG.debug("{}", 50 / i), ArithmeticException.class));
|
||||
}
|
||||
|
||||
@Test(expected = RuntimeException.class)
|
||||
public void whenExceptionFromThrowingConsumerWrapper_thenSuccess() {
|
||||
integers.forEach(throwingConsumerWrapper(i -> writeToFile(i)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNoExceptionFromHandlingConsumerWrapper_thenSuccess() {
|
||||
integers.forEach(handlingConsumerWrapper(i -> writeToFile(i), IOException.class));
|
||||
}
|
||||
|
||||
private void writeToFile(Integer i) throws IOException {
|
||||
if (i == 0) {
|
||||
throw new IOException(); // mock IOException
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,261 +0,0 @@
|
||||
package com.baeldung.java8.optional;
|
||||
|
||||
import com.baeldung.optional.Modem;
|
||||
import com.baeldung.optional.Person;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class OptionalUnitTest {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(OptionalUnitTest.class);
|
||||
|
||||
// creating Optional
|
||||
@Test
|
||||
public void whenCreatesEmptyOptional_thenCorrect() {
|
||||
Optional<String> empty = Optional.empty();
|
||||
assertFalse(empty.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonNull_whenCreatesNonNullable_thenCorrect() {
|
||||
String name = "baeldung";
|
||||
Optional.of(name);
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void givenNull_whenThrowsErrorOnCreate_thenCorrect() {
|
||||
String name = null;
|
||||
Optional<String> opt = Optional.of(name);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonNull_whenCreatesOptional_thenCorrect() {
|
||||
String name = "baeldung";
|
||||
Optional<String> opt = Optional.of(name);
|
||||
assertEquals("Optional[baeldung]", opt.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonNull_whenCreatesNullable_thenCorrect() {
|
||||
String name = "baeldung";
|
||||
Optional<String> opt = Optional.ofNullable(name);
|
||||
assertEquals("Optional[baeldung]", opt.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNull_whenCreatesNullable_thenCorrect() {
|
||||
String name = null;
|
||||
Optional<String> opt = Optional.ofNullable(name);
|
||||
assertEquals("Optional.empty", opt.toString());
|
||||
}
|
||||
// Checking Value With isPresent()
|
||||
|
||||
@Test
|
||||
public void givenOptional_whenIsPresentWorks_thenCorrect() {
|
||||
Optional<String> opt = Optional.of("Baeldung");
|
||||
assertTrue(opt.isPresent());
|
||||
|
||||
opt = Optional.ofNullable(null);
|
||||
assertFalse(opt.isPresent());
|
||||
}
|
||||
|
||||
// Condition Action With ifPresent()
|
||||
@Test
|
||||
public void givenOptional_whenIfPresentWorks_thenCorrect() {
|
||||
Optional<String> opt = Optional.of("baeldung");
|
||||
opt.ifPresent(name -> LOG.debug("{}", name.length()));
|
||||
}
|
||||
|
||||
// returning Value With get()
|
||||
@Test
|
||||
public void givenOptional_whenGetsValue_thenCorrect() {
|
||||
Optional<String> opt = Optional.of("baeldung");
|
||||
String name = opt.get();
|
||||
assertEquals("baeldung", name);
|
||||
}
|
||||
|
||||
@Test(expected = NoSuchElementException.class)
|
||||
public void givenOptionalWithNull_whenGetThrowsException_thenCorrect() {
|
||||
Optional<String> opt = Optional.ofNullable(null);
|
||||
String name = opt.get();
|
||||
}
|
||||
|
||||
// Conditional Return With filter()
|
||||
@Test
|
||||
public void whenOptionalFilterWorks_thenCorrect() {
|
||||
Integer year = 2016;
|
||||
Optional<Integer> yearOptional = Optional.of(year);
|
||||
boolean is2016 = yearOptional.filter(y -> y == 2016)
|
||||
.isPresent();
|
||||
assertTrue(is2016);
|
||||
boolean is2017 = yearOptional.filter(y -> y == 2017)
|
||||
.isPresent();
|
||||
assertFalse(is2017);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFiltersWithoutOptional_thenCorrect() {
|
||||
assertTrue(priceIsInRange1(new Modem(10.0)));
|
||||
assertFalse(priceIsInRange1(new Modem(9.9)));
|
||||
assertFalse(priceIsInRange1(new Modem(null)));
|
||||
assertFalse(priceIsInRange1(new Modem(15.5)));
|
||||
assertFalse(priceIsInRange1(null));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFiltersWithOptional_thenCorrect() {
|
||||
assertTrue(priceIsInRange2(new Modem(10.0)));
|
||||
assertFalse(priceIsInRange2(new Modem(9.9)));
|
||||
assertFalse(priceIsInRange2(new Modem(null)));
|
||||
assertFalse(priceIsInRange2(new Modem(15.5)));
|
||||
assertFalse(priceIsInRange1(null));
|
||||
}
|
||||
|
||||
public boolean priceIsInRange1(Modem modem) {
|
||||
boolean isInRange = false;
|
||||
if (modem != null && modem.getPrice() != null && (modem.getPrice() >= 10 && modem.getPrice() <= 15)) {
|
||||
isInRange = true;
|
||||
}
|
||||
return isInRange;
|
||||
}
|
||||
|
||||
public boolean priceIsInRange2(Modem modem2) {
|
||||
return Optional.ofNullable(modem2)
|
||||
.map(Modem::getPrice)
|
||||
.filter(p -> p >= 10)
|
||||
.filter(p -> p <= 15)
|
||||
.isPresent();
|
||||
}
|
||||
|
||||
// Transforming Value With map()
|
||||
@Test
|
||||
public void givenOptional_whenMapWorks_thenCorrect() {
|
||||
List<String> companyNames = Arrays.asList("paypal", "oracle", "", "microsoft", "", "apple");
|
||||
Optional<List<String>> listOptional = Optional.of(companyNames);
|
||||
|
||||
int size = listOptional.map(List::size)
|
||||
.orElse(0);
|
||||
assertEquals(6, size);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOptional_whenMapWorks_thenCorrect2() {
|
||||
String name = "baeldung";
|
||||
Optional<String> nameOptional = Optional.of(name);
|
||||
|
||||
int len = nameOptional.map(String::length)
|
||||
.orElse(0);
|
||||
assertEquals(8, len);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOptional_whenMapWorksWithFilter_thenCorrect() {
|
||||
String password = " password ";
|
||||
Optional<String> passOpt = Optional.of(password);
|
||||
boolean correctPassword = passOpt.filter(pass -> pass.equals("password"))
|
||||
.isPresent();
|
||||
assertFalse(correctPassword);
|
||||
|
||||
correctPassword = passOpt.map(String::trim)
|
||||
.filter(pass -> pass.equals("password"))
|
||||
.isPresent();
|
||||
assertTrue(correctPassword);
|
||||
}
|
||||
|
||||
// Transforming Value With flatMap()
|
||||
@Test
|
||||
public void givenOptional_whenFlatMapWorks_thenCorrect2() {
|
||||
Person person = new Person("john", 26);
|
||||
Optional<Person> personOptional = Optional.of(person);
|
||||
|
||||
Optional<Optional<String>> nameOptionalWrapper = personOptional.map(Person::getName);
|
||||
Optional<String> nameOptional = nameOptionalWrapper.orElseThrow(IllegalArgumentException::new);
|
||||
String name1 = nameOptional.orElseThrow(IllegalArgumentException::new);
|
||||
assertEquals("john", name1);
|
||||
|
||||
String name = personOptional.flatMap(Person::getName)
|
||||
.orElseThrow(IllegalArgumentException::new);
|
||||
assertEquals("john", name);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOptional_whenFlatMapWorksWithFilter_thenCorrect() {
|
||||
Person person = new Person("john", 26);
|
||||
person.setPassword("password");
|
||||
Optional<Person> personOptional = Optional.of(person);
|
||||
|
||||
String password = personOptional.flatMap(Person::getPassword)
|
||||
.filter(cleanPass -> cleanPass.equals("password"))
|
||||
.orElseThrow(IllegalArgumentException::new);
|
||||
assertEquals("password", password);
|
||||
}
|
||||
|
||||
// Default Value With orElse
|
||||
@Test
|
||||
public void whenOrElseWorks_thenCorrect() {
|
||||
String nullName = null;
|
||||
String name = Optional.ofNullable(nullName)
|
||||
.orElse("john");
|
||||
assertEquals("john", name);
|
||||
}
|
||||
|
||||
// Default Value With orElseGet
|
||||
@Test
|
||||
public void whenOrElseGetWorks_thenCorrect() {
|
||||
String nullName = null;
|
||||
String name = Optional.ofNullable(nullName)
|
||||
.orElseGet(() -> "john");
|
||||
assertEquals("john", name);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenOrElseGetAndOrElseOverlap_thenCorrect() {
|
||||
String text = null;
|
||||
LOG.debug("Using orElseGet:");
|
||||
String defaultText = Optional.ofNullable(text)
|
||||
.orElseGet(this::getMyDefault);
|
||||
assertEquals("Default Value", defaultText);
|
||||
|
||||
LOG.debug("Using orElse:");
|
||||
defaultText = Optional.ofNullable(text)
|
||||
.orElse(getMyDefault());
|
||||
assertEquals("Default Value", defaultText);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenOrElseGetAndOrElseDiffer_thenCorrect() {
|
||||
String text = "Text present";
|
||||
LOG.debug("Using orElseGet:");
|
||||
String defaultText = Optional.ofNullable(text)
|
||||
.orElseGet(this::getMyDefault);
|
||||
assertEquals("Text present", defaultText);
|
||||
|
||||
LOG.debug("Using orElse:");
|
||||
defaultText = Optional.ofNullable(text)
|
||||
.orElse(getMyDefault());
|
||||
assertEquals("Text present", defaultText);
|
||||
}
|
||||
|
||||
// Exceptions With orElseThrow
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void whenOrElseThrowWorks_thenCorrect() {
|
||||
String nullName = null;
|
||||
String name = Optional.ofNullable(nullName)
|
||||
.orElseThrow(IllegalArgumentException::new);
|
||||
}
|
||||
|
||||
public String getMyDefault() {
|
||||
LOG.debug("Getting default value...");
|
||||
return "Default Value";
|
||||
}
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
### Relevant Articles:
|
||||
- [Guide To Java 8 Optional](http://www.baeldung.com/java-optional)
|
||||
@@ -1,75 +0,0 @@
|
||||
package com.baeldung.strategy;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static com.baeldung.strategy.Discounter.christmas;
|
||||
import static com.baeldung.strategy.Discounter.easter;
|
||||
import static com.baeldung.strategy.Discounter.newYear;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class StrategyDesignPatternUnitTest {
|
||||
@Test
|
||||
public void shouldDivideByTwo_WhenApplyingStaffDiscounter() {
|
||||
Discounter staffDiscounter = new EasterDiscounter();
|
||||
|
||||
final BigDecimal discountedValue = staffDiscounter
|
||||
.apply(BigDecimal.valueOf(100));
|
||||
|
||||
assertThat(discountedValue)
|
||||
.isEqualByComparingTo(BigDecimal.valueOf(50));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldDivideByTwo_WhenApplyingStaffDiscounterWithAnonyousTypes() {
|
||||
Discounter staffDiscounter = new Discounter() {
|
||||
@Override
|
||||
public BigDecimal apply(BigDecimal amount) {
|
||||
return amount.multiply(BigDecimal.valueOf(0.5));
|
||||
}
|
||||
};
|
||||
|
||||
final BigDecimal discountedValue = staffDiscounter
|
||||
.apply(BigDecimal.valueOf(100));
|
||||
|
||||
assertThat(discountedValue)
|
||||
.isEqualByComparingTo(BigDecimal.valueOf(50));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldDivideByTwo_WhenApplyingStaffDiscounterWithLamda() {
|
||||
Discounter staffDiscounter = amount -> amount.multiply(BigDecimal.valueOf(0.5));
|
||||
|
||||
final BigDecimal discountedValue = staffDiscounter
|
||||
.apply(BigDecimal.valueOf(100));
|
||||
|
||||
assertThat(discountedValue)
|
||||
.isEqualByComparingTo(BigDecimal.valueOf(50));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldApplyAllDiscounts() {
|
||||
List<Discounter> discounters = Arrays.asList(christmas(), newYear(), easter());
|
||||
|
||||
BigDecimal amount = BigDecimal.valueOf(100);
|
||||
|
||||
final Discounter combinedDiscounter = discounters
|
||||
.stream()
|
||||
.reduce(v -> v, Discounter::combine);
|
||||
|
||||
combinedDiscounter.apply(amount);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldChainDiscounters() {
|
||||
final Function<BigDecimal, BigDecimal> combinedDiscounters = Discounter
|
||||
.christmas()
|
||||
.andThen(newYear());
|
||||
|
||||
combinedDiscounters.apply(BigDecimal.valueOf(100));
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class InfiniteStreamUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenInfiniteStream_whenUseIntermediateLimitMethod_thenShouldTerminateInFiniteTime() {
|
||||
//given
|
||||
Stream<Integer> infiniteStream = Stream.iterate(0, i -> i + 2);
|
||||
|
||||
//when
|
||||
List<Integer> collect = infiniteStream
|
||||
.limit(10)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
//then
|
||||
assertEquals(collect, Arrays.asList(0, 2, 4, 6, 8, 10, 12, 14, 16, 18));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInfiniteStreamOfRandomInts_whenUseLimit_shouldTerminateInFiniteTime() {
|
||||
//given
|
||||
Supplier<UUID> randomUUIDSupplier = UUID::randomUUID;
|
||||
Stream<UUID> infiniteStreamOfRandomUUID = Stream.generate(randomUUIDSupplier);
|
||||
|
||||
//when
|
||||
List<UUID> randomInts = infiniteStreamOfRandomUUID
|
||||
.skip(10)
|
||||
.limit(10)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
//then
|
||||
assertEquals(randomInts.size(), 10);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StreamAddUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenStream_whenAppendingObject_thenAppended() {
|
||||
Stream<String> anStream = Stream.of("a", "b", "c", "d", "e");
|
||||
|
||||
Stream<String> newStream = Stream.concat(anStream, Stream.of("A"));
|
||||
|
||||
List<String> resultList = newStream.collect(Collectors.toList());
|
||||
assertEquals(resultList.get(resultList.size() - 1), "A");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStream_whenPrependingObject_thenPrepended() {
|
||||
Stream<Integer> anStream = Stream.of(1, 2, 3, 4, 5);
|
||||
|
||||
Stream<Integer> newStream = Stream.concat(Stream.of(99), anStream);
|
||||
|
||||
assertEquals(newStream.findFirst()
|
||||
.get(), (Integer) 99);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStream_whenInsertingObject_thenInserted() {
|
||||
Stream<Double> anStream = Stream.of(1.1, 2.2, 3.3);
|
||||
|
||||
Stream<Double> newStream = insertInStream(anStream, 9.9, 3);
|
||||
|
||||
List<Double> resultList = newStream.collect(Collectors.toList());
|
||||
assertEquals(resultList.get(3), (Double) 9.9);
|
||||
}
|
||||
|
||||
private <T> Stream<T> insertInStream(Stream<T> stream, T elem, int index) {
|
||||
List<T> result = stream.collect(Collectors.toList());
|
||||
result.add(index, elem);
|
||||
return result.stream();
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StreamApiTest {
|
||||
|
||||
@Test
|
||||
public void givenList_whenGetLastElementUsingReduce_thenReturnLastElement() {
|
||||
List<String> valueList = new ArrayList<>();
|
||||
valueList.add("Joe");
|
||||
valueList.add("John");
|
||||
valueList.add("Sean");
|
||||
|
||||
String last = StreamApi.getLastElementUsingReduce(valueList);
|
||||
|
||||
assertEquals("Sean", last);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInfiniteStream_whenGetInfiniteStreamLastElementUsingReduce_thenReturnLastElement() {
|
||||
int last = StreamApi.getInfiniteStreamLastElementUsingReduce();
|
||||
assertEquals(19, last);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListAndCount_whenGetLastElementUsingSkip_thenReturnLastElement() {
|
||||
List<String> valueList = new ArrayList<>();
|
||||
valueList.add("Joe");
|
||||
valueList.add("John");
|
||||
valueList.add("Sean");
|
||||
|
||||
String last = StreamApi.getLastElementUsingSkip(valueList);
|
||||
|
||||
assertEquals("Sean", last);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import static java.util.stream.Collectors.collectingAndThen;
|
||||
import static java.util.stream.Collectors.toList;
|
||||
import static java.util.stream.Collectors.toSet;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.stream.mycollectors.MyImmutableListCollector;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
|
||||
public class StreamToImmutableTest {
|
||||
|
||||
@Test
|
||||
public void whenUsingCollectingToImmutableSet_thenSuccess() {
|
||||
List<String> givenList = Arrays.asList("a", "b", "c");
|
||||
List<String> result = givenList.stream()
|
||||
.collect(collectingAndThen(toSet(), ImmutableList::copyOf));
|
||||
|
||||
System.out.println(result.getClass());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCollectingToUnmodifiableList_thenSuccess() {
|
||||
List<String> givenList = new ArrayList<>(Arrays.asList("a", "b", "c"));
|
||||
List<String> result = givenList.stream()
|
||||
.collect(collectingAndThen(toList(), Collections::unmodifiableList));
|
||||
|
||||
System.out.println(result.getClass());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectToImmutableList_thenSuccess() {
|
||||
List<Integer> list = IntStream.range(0, 9)
|
||||
.boxed()
|
||||
.collect(ImmutableList.toImmutableList());
|
||||
|
||||
System.out.println(list.getClass());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectToMyImmutableListCollector_thenSuccess() {
|
||||
List<String> givenList = Arrays.asList("a", "b", "c", "d");
|
||||
List<String> result = givenList.stream()
|
||||
.collect(MyImmutableListCollector.toImmutableList());
|
||||
|
||||
System.out.println(result.getClass());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPassingSupplier_thenSuccess() {
|
||||
List<String> givenList = Arrays.asList("a", "b", "c", "d");
|
||||
List<String> result = givenList.stream()
|
||||
.collect(MyImmutableListCollector.toImmutableList(LinkedList::new));
|
||||
|
||||
System.out.println(result.getClass());
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package com.baeldung.stream.mycollectors;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collector;
|
||||
|
||||
public class MyImmutableListCollector {
|
||||
|
||||
public static <T, A extends List<T>> Collector<T, A, List<T>> toImmutableList(Supplier<A> supplier) {
|
||||
return Collector.of(supplier, List::add, (left, right) -> {
|
||||
left.addAll(right);
|
||||
return left;
|
||||
}, Collections::unmodifiableList);
|
||||
}
|
||||
|
||||
public static <T> Collector<T, List<T>, List<T>> toImmutableList() {
|
||||
return toImmutableList(ArrayList::new);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class JoinerSplitterUnitTest {
|
||||
|
||||
@Test
|
||||
public void provided_array_convert_to_stream_and_convert_to_string() {
|
||||
|
||||
String[] programming_languages = {"java", "python", "nodejs", "ruby"};
|
||||
|
||||
String expectation = "java,python,nodejs,ruby";
|
||||
|
||||
String result = JoinerSplitter.join(programming_languages);
|
||||
assertEquals(result, expectation);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArray_transformedToStream_convertToPrefixPostfixString() {
|
||||
|
||||
String[] programming_languages = {"java", "python",
|
||||
"nodejs", "ruby"};
|
||||
String expectation = "[java,python,nodejs,ruby]";
|
||||
|
||||
String result = JoinerSplitter.joinWithPrefixPostFix(programming_languages);
|
||||
assertEquals(result, expectation);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_transformedToStream_convertToList() {
|
||||
|
||||
String programming_languages = "java,python,nodejs,ruby";
|
||||
|
||||
List<String> expectation = new ArrayList<String>();
|
||||
expectation.add("java");
|
||||
expectation.add("python");
|
||||
expectation.add("nodejs");
|
||||
expectation.add("ruby");
|
||||
|
||||
List<String> result = JoinerSplitter.split(programming_languages);
|
||||
|
||||
assertEquals(result, expectation);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_transformedToStream_convertToListOfChar() {
|
||||
|
||||
String programming_languages = "java,python,nodejs,ruby";
|
||||
|
||||
List<Character> expectation = new ArrayList<Character>();
|
||||
char[] charArray = programming_languages.toCharArray();
|
||||
for (char c : charArray) {
|
||||
expectation.add(c);
|
||||
}
|
||||
|
||||
List<Character> result = JoinerSplitter.splitToListOfChar(programming_languages);
|
||||
assertEquals(result, expectation);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package com.baeldung.temporaladjusters;
|
||||
|
||||
import com.baeldung.temporaladjuster.CustomTemporalAdjuster;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.Period;
|
||||
import java.time.temporal.TemporalAdjuster;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class CustomTemporalAdjusterTest {
|
||||
|
||||
private static final TemporalAdjuster NEXT_WORKING_DAY = new CustomTemporalAdjuster();
|
||||
|
||||
@Test
|
||||
public void whenAdjustAndImplementInterface_thenNextWorkingDay() {
|
||||
LocalDate localDate = LocalDate.of(2017, 07, 8);
|
||||
CustomTemporalAdjuster temporalAdjuster = new CustomTemporalAdjuster();
|
||||
LocalDate nextWorkingDay = localDate.with(temporalAdjuster);
|
||||
|
||||
assertEquals("2017-07-10", nextWorkingDay.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAdjust_thenNextWorkingDay() {
|
||||
LocalDate localDate = LocalDate.of(2017, 07, 8);
|
||||
LocalDate date = localDate.with(NEXT_WORKING_DAY);
|
||||
|
||||
assertEquals("2017-07-10", date.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAdjust_thenFourteenDaysAfterDate() {
|
||||
LocalDate localDate = LocalDate.of(2017, 07, 8);
|
||||
TemporalAdjuster temporalAdjuster = (t) -> t.plus(Period.ofDays(14));
|
||||
LocalDate result = localDate.with(temporalAdjuster);
|
||||
|
||||
String fourteenDaysAfterDate = "2017-07-22";
|
||||
|
||||
assertEquals(fourteenDaysAfterDate, result.toString());
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package com.baeldung.temporaladjusters;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.LocalDate;
|
||||
import java.time.temporal.TemporalAdjusters;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class TemporalAdjustersTest {
|
||||
|
||||
@Test
|
||||
public void whenAdjust_thenNextSunday() {
|
||||
LocalDate localDate = LocalDate.of(2017, 07, 8);
|
||||
LocalDate nextSunday = localDate.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
|
||||
|
||||
String expected = "2017-07-09";
|
||||
|
||||
Assert.assertEquals(expected, nextSunday.toString());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
package com.baeldung.util;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.temporal.ChronoField;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class CurrentDateTimeUnitTest {
|
||||
|
||||
private static final Clock clock = Clock.fixed(Instant.parse("2016-10-09T15:10:30.00Z"), ZoneId.of("UTC"));
|
||||
|
||||
@Test
|
||||
public void shouldReturnCurrentDate() {
|
||||
final LocalDate now = LocalDate.now(clock);
|
||||
|
||||
assertEquals(9, now.get(ChronoField.DAY_OF_MONTH));
|
||||
assertEquals(10, now.get(ChronoField.MONTH_OF_YEAR));
|
||||
assertEquals(2016, now.get(ChronoField.YEAR));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnCurrentTime() {
|
||||
final LocalTime now = LocalTime.now(clock);
|
||||
|
||||
assertEquals(15, now.get(ChronoField.HOUR_OF_DAY));
|
||||
assertEquals(10, now.get(ChronoField.MINUTE_OF_HOUR));
|
||||
assertEquals(30, now.get(ChronoField.SECOND_OF_MINUTE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnCurrentTimestamp() {
|
||||
final Instant now = Instant.now(clock);
|
||||
|
||||
assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond());
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user