|
| 1 | +package com.winterbe.java8; |
| 2 | + |
| 3 | +import java.util.Comparator; |
| 4 | +import java.util.Objects; |
| 5 | +import java.util.UUID; |
| 6 | +import java.util.concurrent.Callable; |
| 7 | +import java.util.function.Consumer; |
| 8 | +import java.util.function.Function; |
| 9 | +import java.util.function.Predicate; |
| 10 | +import java.util.function.Supplier; |
| 11 | + |
| 12 | +/** |
| 13 | + * Common standard functions from the Java API. |
| 14 | + * |
| 15 | + * @author Benjamin Winterberg |
| 16 | + */ |
| 17 | +public class Lambda3 { |
| 18 | + |
| 19 | + @FunctionalInterface |
| 20 | + interface Fun { |
| 21 | + void foo(); |
| 22 | + } |
| 23 | + |
| 24 | + public static void main(String[] args) throws Exception { |
| 25 | + |
| 26 | + // Predicates |
| 27 | + |
| 28 | + Predicate<String> predicate = (s) -> s.length() > 0; |
| 29 | + |
| 30 | + predicate.test("foo"); // true |
| 31 | + predicate.negate().test("foo"); // false |
| 32 | + |
| 33 | + Predicate<Boolean> nonNull = Objects::nonNull; |
| 34 | + Predicate<Boolean> isNull = Objects::isNull; |
| 35 | + |
| 36 | + Predicate<String> isEmpty = String::isEmpty; |
| 37 | + Predicate<String> isNotEmpty = isEmpty.negate(); |
| 38 | + |
| 39 | + |
| 40 | + // Functions |
| 41 | + |
| 42 | + Function<String, Integer> toInteger = Integer::valueOf; |
| 43 | + Function<String, String> backToString = toInteger.andThen(String::valueOf); |
| 44 | + |
| 45 | + backToString.apply("123"); // "123" |
| 46 | + |
| 47 | + |
| 48 | + // Suppliers |
| 49 | + |
| 50 | + Supplier<Person> personSupplier = Person::new; |
| 51 | + personSupplier.get(); // new Person |
| 52 | + |
| 53 | + |
| 54 | + // Consumers |
| 55 | + |
| 56 | + Consumer<Person> greeter = (p) -> System.out.println("Hello, " + p.firstName); |
| 57 | + greeter.accept(new Person("Luke", "Skywalker")); |
| 58 | + |
| 59 | + |
| 60 | + |
| 61 | + // Comparators |
| 62 | + |
| 63 | + Comparator<Person> comparator = (p1, p2) -> p1.firstName.compareTo(p2.firstName); |
| 64 | + |
| 65 | + Person p1 = new Person("John", "Doe"); |
| 66 | + Person p2 = new Person("Alice", "Wonderland"); |
| 67 | + |
| 68 | + comparator.compare(p1, p2); // > 0 |
| 69 | + comparator.reversed().compare(p1, p2); // < 0 |
| 70 | + |
| 71 | + |
| 72 | + // Runnables |
| 73 | + |
| 74 | + Runnable runnable = () -> System.out.println(UUID.randomUUID()); |
| 75 | + runnable.run(); |
| 76 | + |
| 77 | + |
| 78 | + // Callables |
| 79 | + |
| 80 | + Callable<UUID> callable = UUID::randomUUID; |
| 81 | + callable.call(); |
| 82 | + } |
| 83 | + |
| 84 | +} |
0 commit comments