Created by Ronen Narkis / @narkirs
(arg1, arg2...) -> { body }
(type1 arg1, type2 arg2...) -> { body }
// with types
(int a, int b) -> { return a + b; }
// ommiting braces
() -> System.out.println("Hello World");
// default return
() -> 42
// or explicit
() -> { return 3.1415 };
new Thread(
() -> System.out.println("hello world")
).start();
Consumer<Integer> c = (int x) -> { System.out.println(x) };
IntConsumer b = (int a) -> a + 1;
String::valueOf == (s) -> String.valueOf(s)
String ex = "hello";
ex::toString == () -> "hello".toString();
String::toString == (s) -> s.toString();
String::new == () -> new String();
Stream<Integer> numbers = IntStream.range(1, 1000);
Stream<Integer> sequential = numbers.map(i -> i + 1).filter(i -> i % 2 == 0);
// forkJoined
Stream<Integer> parallel = seqential.parallel();
List<Integer> list = sequential.limit(10).collect(toList());
public interface Loggable {
default Logger logger() {
return Logger.getLogger(this.getClass());
}
}
public interface Metrics {
default void report(String key, int metric) {
return Metric.getInstance().send(key,metric);
}
}
public class Foo implements Loggable, Metrics {
public Integer doSomething() {
logger().info("doing something");
report("call made to doSomething",1);
...
}
}
ExecutorService service = Executors.newCachedThreadPool();
CompletableFuture<String> first =
CompletableFuture.supplyAsync(longRunning, service);
CompletableFuture<String> second =
CompletableFuture.supplyAsync(longRunning, service);
CompletableFuture<String> combined =
first.thenCombineAsync(second, (f, s) -> f + " " + s, service);
Function<String,CompletableFuture<String>> upper =
s -> CompletableFuture.completedFuture(s.toUpperCase());
CompletableFuture<String> result = combined.thenCompose(upper);
System.out.println(result.get());