Java 8

Calling one lambda at a time

Created by Ronen Narkis / @narkirs

History

  • Initial beta 1995!
  • Java 8 March 2014
  • Java 9 was 2016 moved to 2017

Overview

  • Lambdas
  • Method refrences
  • Streams
  • Default methods (Aka Traits)
  • CompletableFuture

Lambda syntax


(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 };
	    

Functional interfaces


new Thread(
  () -> System.out.println("hello world")
).start();

Consumer<Integer>  c = (int x) -> { System.out.println(x) };

IntConsumer b = (int a) -> a + 1;


	    

Method refrences



String::valueOf ==  (s) -> String.valueOf(s)

String ex = "hello";

ex::toString ==  () -> "hello".toString();

String::toString ==  (s) -> s.toString();

String::new ==  () -> new String();

	    

Streams



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());

	    

Default methods


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);
    }
}

	    

Mixing defaults


public class Foo implements Loggable, Metrics {
    public Integer doSomething() {
	  logger().info("doing something");
	  report("call made to doSomething",1);
	  ...
    }
}
	    

Completable Futures (Aka Promises)


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());

	    

Summary