|
| 1 | +packagecom.winterbe.java8; |
| 2 | + |
| 3 | +importjava.util.Comparator; |
| 4 | +importjava.util.Objects; |
| 5 | +importjava.util.UUID; |
| 6 | +importjava.util.concurrent.Callable; |
| 7 | +importjava.util.function.Consumer; |
| 8 | +importjava.util.function.Function; |
| 9 | +importjava.util.function.Predicate; |
| 10 | +importjava.util.function.Supplier; |
| 11 | + |
| 12 | +/** |
| 13 | + * Common standard functions from the Java API. |
| 14 | + * |
| 15 | + * @author Benjamin Winterberg |
| 16 | + */ |
| 17 | +publicclassLambda3 { |
| 18 | + |
| 19 | +@FunctionalInterface |
| 20 | +interfaceFun { |
| 21 | +voidfoo(); |
| 22 | + } |
| 23 | + |
| 24 | +publicstaticvoidmain(String[]args)throwsException { |
| 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(newPerson("Luke","Skywalker")); |
| 58 | + |
| 59 | + |
| 60 | + |
| 61 | +// Comparators |
| 62 | + |
| 63 | +Comparator<Person>comparator = (p1,p2) ->p1.firstName.compareTo(p2.firstName); |
| 64 | + |
| 65 | +Personp1 =newPerson("John","Doe"); |
| 66 | +Personp2 =newPerson("Alice","Wonderland"); |
| 67 | + |
| 68 | +comparator.compare(p1,p2);// > 0 |
| 69 | +comparator.reversed().compare(p1,p2);// < 0 |
| 70 | + |
| 71 | + |
| 72 | +// Runnables |
| 73 | + |
| 74 | +Runnablerunnable = () ->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 | +} |