What's new in java 8

Post on 16-Apr-2017

29 Views

Category:

Technology

0 Downloads

Preview:

Click to see full reader

Transcript

What’s New in Java 8Lambda, Default Methods, and Streams

What’s New in Java 8

● Lambda Expression● Default Methods● Streams● Optional● Nashorn● New Date and Time API● No More PermGen

What’s New in Java 8

● Lambda Expression● Default Methods● Streams● Optional● Nashorn● New Date and Time API● No More PermGen

Java 9 has been scheduled for general availability in 2017

Lambda Expression and Method Reference

Lambda Expression

A lambda expression is like syntactic sugar for an anonymous class with one method

Lambda Expression - Syntax

() -> body

parameter -> body

(parameters) -> body

Lambda Expression - Syntax Example

() -> { System.out.println(“Hello”); }

(int i) -> System.out.println(i)

(double d1, double d2) -> Double.compare(d1, d2)

Lambda Expression - Method References

A method references is the shorthand syntax for a lambda expression that executes just one

method

Lambda Expression - Method References

Sometimes lambda expression is just a call to some method

list.forEach(s -> System.out.println(s));

Lambda Expression - Method References

You can turn that lambda expression into method reference

list.forEach(System.out::println);

Lambda Expression - Method References

Consumer<String> consumer = (s) -> { System.out.println(s)};

Consumer<String> consumer = System.out::println;

Default Methods

Default Methods

Default methods enable you to add new functionality to the interfaces of your libraries

and ensure binary compatibility with code written for older versions of those interfaces.

Default Methods - Example

public interface Iterable<T> { Iterator<T> iterator(); default void forEach(Consumer<? super T> action) { Objects.requireNonNull(action); for (T t : this) { action.accept(t); } } default Spliterator<T> spliterator() { ... }}

Static MethodsYou can define static methods in interfaces!

Static Methods - Example

public interface Vertx extends Measured { static Vertx vertx() { return factory.vertx(); } ... VertxFactory factory = ServiceHelper.loadFactory(VertxFactory.class);}

Static Methods - Example

Vertx vertx = Vertx.vertx();

Static Methods - Example

Vertx vertx = Vertx.vertx();

Streams

Streams

A sequence of elements supporting sequential and parallel aggregate operations.

Streams - Example

int sum = widgets.stream() .filter(w -> w.getColor() == RED) .mapToInt(w -> w.getWeight()) .sum();

Streams - Example

int sum = widgets.parallelStream() .filter(w -> w.getColor() == RED) .mapToInt(w -> w.getWeight()) .sum();

?

Thank You

top related