BAEL-2904 Improvement: Move Lambda Related Articles (#7519)
This commit is contained in:
committed by
Josh Cummings
parent
243882bf15
commit
2a9050ef90
@@ -1,3 +1,8 @@
|
||||
## Relevant articles:
|
||||
|
||||
- [Why Do Local Variables Used in Lambdas Have to Be Final or Effectively Final?](https://www.baeldung.com/java-lambda-effectively-final-local-variables)
|
||||
- [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda)
|
||||
- [Functional Interfaces in Java 8](http://www.baeldung.com/java-8-functional-interfaces)
|
||||
- [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips)
|
||||
- [Exceptions in Java 8 Lambda Expressions](http://www.baeldung.com/java-lambda-exceptions)
|
||||
- [Method References in Java](https://www.baeldung.com/java-method-references)
|
||||
|
||||
@@ -15,5 +15,11 @@
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
@@ -0,0 +1,89 @@
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.java8.lambda.exceptions;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface ThrowingConsumer<T, E extends Exception> {
|
||||
|
||||
void accept(T t) throws E;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.java8.lambda.tips;
|
||||
|
||||
|
||||
@FunctionalInterface
|
||||
public interface Bar {
|
||||
|
||||
String method(String string);
|
||||
|
||||
default String defaultMethod() {
|
||||
return "String from Bar";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.java8.lambda.tips;
|
||||
|
||||
|
||||
@FunctionalInterface
|
||||
public interface Baz {
|
||||
|
||||
String method(String string);
|
||||
|
||||
default String defaultMethod() {
|
||||
return "String from Baz";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.java8.lambda.tips;
|
||||
|
||||
|
||||
@FunctionalInterface
|
||||
public interface Foo {
|
||||
|
||||
String method(String string);
|
||||
|
||||
default void defaultMethod() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.java8.lambda.tips;
|
||||
|
||||
|
||||
@FunctionalInterface
|
||||
public interface FooExtended extends Baz, Bar {
|
||||
|
||||
@Override
|
||||
default String defaultMethod() {
|
||||
return Bar.super.defaultMethod();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.java8.lambda.tips;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public interface Processor {
|
||||
|
||||
String processWithCallable(Callable<String> c) throws Exception;
|
||||
|
||||
String processWithSupplier(Supplier<String> s);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.java8.lambda.tips;
|
||||
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class ProcessorImpl implements Processor {
|
||||
|
||||
@Override
|
||||
public String processWithCallable(Callable<String> c) throws Exception {
|
||||
return c.call();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String processWithSupplier(Supplier<String> s) {
|
||||
return s.get();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.java8.lambda.tips;
|
||||
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.functionalinterface;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface ShortToByteFunction {
|
||||
|
||||
byte applyAsByte(short s);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package com.baeldung.java8;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.java8.entity.Human;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.primitives.Ints;
|
||||
|
||||
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)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenStreamNaturalOrdering_whenSortingEntitiesByName_thenCorrectlySorted() {
|
||||
final List<String> letters = Lists.newArrayList("B", "A", "C");
|
||||
|
||||
final List<String> sortedLetters = letters.stream().sorted().collect(Collectors.toList());
|
||||
Assert.assertThat(sortedLetters.get(0), equalTo("A"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenStreamCustomOrdering_whenSortingEntitiesByName_thenCorrectlySorted() {
|
||||
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
|
||||
final Comparator<Human> nameComparator = (h1, h2) -> h1.getName().compareTo(h2.getName());
|
||||
|
||||
final List<Human> sortedHumans = humans.stream().sorted(nameComparator).collect(Collectors.toList());
|
||||
Assert.assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenStreamComparatorOrdering_whenSortingEntitiesByName_thenCorrectlySorted() {
|
||||
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
|
||||
|
||||
final List<Human> sortedHumans = humans.stream().sorted(Comparator.comparing(Human::getName)).collect(Collectors.toList());
|
||||
Assert.assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenStreamNaturalOrdering_whenSortingEntitiesByNameReversed_thenCorrectlySorted() {
|
||||
final List<String> letters = Lists.newArrayList("B", "A", "C");
|
||||
|
||||
final List<String> reverseSortedLetters = letters.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
|
||||
Assert.assertThat(reverseSortedLetters.get(0), equalTo("C"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenStreamCustomOrdering_whenSortingEntitiesByNameReversed_thenCorrectlySorted() {
|
||||
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
|
||||
final Comparator<Human> reverseNameComparator = (h1, h2) -> h2.getName().compareTo(h1.getName());
|
||||
|
||||
final List<Human> reverseSortedHumans = humans.stream().sorted(reverseNameComparator).collect(Collectors.toList());
|
||||
Assert.assertThat(reverseSortedHumans.get(0), equalTo(new Human("Sarah", 10)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenStreamComparatorOrdering_whenSortingEntitiesByNameReversed_thenCorrectlySorted() {
|
||||
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
|
||||
|
||||
final List<Human> reverseSortedHumans = humans.stream().sorted(Comparator.comparing(Human::getName, Comparator.reverseOrder())).collect(Collectors.toList());
|
||||
Assert.assertThat(reverseSortedHumans.get(0), equalTo(new Human("Sarah", 10)));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.java8.lambda.methodreference;
|
||||
|
||||
public class Bicycle {
|
||||
|
||||
private String brand;
|
||||
private Integer frameSize;
|
||||
|
||||
public Bicycle(String brand) {
|
||||
this.brand = brand;
|
||||
this.frameSize = 0;
|
||||
}
|
||||
|
||||
public Bicycle(String brand, Integer frameSize) {
|
||||
this.brand = brand;
|
||||
this.frameSize = frameSize;
|
||||
}
|
||||
|
||||
public String getBrand() {
|
||||
return brand;
|
||||
}
|
||||
|
||||
public void setBrand(String brand) {
|
||||
this.brand = brand;
|
||||
}
|
||||
|
||||
public Integer getFrameSize() {
|
||||
return frameSize;
|
||||
}
|
||||
|
||||
public void setFrameSize(Integer frameSize) {
|
||||
this.frameSize = frameSize;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.java8.lambda.methodreference;
|
||||
|
||||
import java.util.Comparator;
|
||||
|
||||
public class BicycleComparator implements Comparator<Bicycle> {
|
||||
|
||||
@Override
|
||||
public int compare(Bicycle a, Bicycle b) {
|
||||
return a.getFrameSize()
|
||||
.compareTo(b.getFrameSize());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.baeldung.java8.lambda.methodreference;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.function.BiFunction;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
public class MethodReferenceUnitTest {
|
||||
|
||||
private static <T> void doNothingAtAll(Object... o) {
|
||||
}
|
||||
|
||||
;
|
||||
|
||||
@Test
|
||||
public void referenceToStaticMethod() {
|
||||
List<String> messages = Arrays.asList("Hello", "Baeldung", "readers!");
|
||||
messages.forEach(word -> StringUtils.capitalize(word));
|
||||
messages.forEach(StringUtils::capitalize);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void referenceToInstanceMethodOfParticularObject() {
|
||||
BicycleComparator bikeFrameSizeComparator = new BicycleComparator();
|
||||
createBicyclesList().stream()
|
||||
.sorted((a, b) -> bikeFrameSizeComparator.compare(a, b));
|
||||
createBicyclesList().stream()
|
||||
.sorted(bikeFrameSizeComparator::compare);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void referenceToInstanceMethodOfArbitratyObjectOfParticularType() {
|
||||
List<Integer> numbers = Arrays.asList(5, 3, 50, 24, 40, 2, 9, 18);
|
||||
numbers.stream()
|
||||
.sorted((a, b) -> Integer.compare(a, b));
|
||||
numbers.stream()
|
||||
.sorted(Integer::compare);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void referenceToConstructor() {
|
||||
BiFunction<String, Integer, Bicycle> bikeCreator = (brand, frameSize) -> new Bicycle(brand, frameSize);
|
||||
BiFunction<String, Integer, Bicycle> bikeCreatorMethodReference = Bicycle::new;
|
||||
List<Bicycle> bikes = new ArrayList<>();
|
||||
bikes.add(bikeCreator.apply("Giant", 50));
|
||||
bikes.add(bikeCreator.apply("Scott", 20));
|
||||
bikes.add(bikeCreatorMethodReference.apply("Trek", 35));
|
||||
bikes.add(bikeCreatorMethodReference.apply("GT", 40));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void referenceToConstructorSimpleExample() {
|
||||
List<String> bikeBrands = Arrays.asList("Giant", "Scott", "Trek", "GT");
|
||||
bikeBrands.stream()
|
||||
.map(Bicycle::new)
|
||||
.toArray(Bicycle[]::new);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void limitationsAndAdditionalExamples() {
|
||||
createBicyclesList().forEach(b -> System.out.printf("Bike brand is '%s' and frame size is '%d'%n", b.getBrand(), b.getFrameSize()));
|
||||
createBicyclesList().forEach((o) -> MethodReferenceUnitTest.doNothingAtAll(o));
|
||||
}
|
||||
|
||||
private List<Bicycle> createBicyclesList() {
|
||||
List<Bicycle> bikes = new ArrayList<>();
|
||||
bikes.add(new Bicycle("Giant", 50));
|
||||
bikes.add(new Bicycle("Scott", 20));
|
||||
bikes.add(new Bicycle("Trek", 35));
|
||||
bikes.add(new Bicycle("GT", 40));
|
||||
return bikes;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package com.baeldung.java8.lambda.tips;
|
||||
|
||||
import com.baeldung.java8.lambda.tips.Foo;
|
||||
import com.baeldung.java8.lambda.tips.FooExtended;
|
||||
import com.baeldung.java8.lambda.tips.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]);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user