Java 8

16
JDK 8 Presented by Vladan Pulec

description

 

Transcript of Java 8

Page 1: Java 8

JDK 8Presented by Vladan Pulec

Page 2: Java 8

2

Java 8

• Estimated JDK release – early 2014 (as of April 18th)• Currently in-progress and described features are still

subject to change• Preview build of IDEA supports Java 8 (

http://confluence.jetbrains.com/display/IDEADEV/EAP)

• Major changes:– Default methods in interfaces– Lambas (anonymous functions)– Streams

Page 3: Java 8

3

Default Methods in Interfaces

• Interfaces can now have default methods – method with concrete implementations and no state

• a lot of core JDK interfaces now have default methods

Page 4: Java 8

4

Functional Interfaces

• A functional interface is an interface with only one abstract method. For example, Runnable interface.

• Can be declared using @FunctionalInterface

Page 5: Java 8

5

Lambda Expressions• What Are they?• Similar to anonymous classes that treat functionality as a method argument, or

code as data.

• btn.setOnAction(new EventHandler<ActionEvent>() {

@Override

public void handle(ActionEvent event) {

System.out.println("Hello World!");

}

});

btn.setOnAction(

event -> System.out.println("Hello World!")

);

Page 6: Java 8

6

Syntax1. A comma-separated list of formal parameters2. The arrow token, -> 3. A body, which consists of a single expression or a statement block

• Note that a return statement is not an expression

• Examples:• two inputs on the left, return block on the right:• (int x, int y) -> { return x + y; } • Single param with inferred type on the left: x -> x * x • no input on the left, return on the right: () -> x

Page 7: Java 8

7

Lambda – Method References (Shorthand forms)

• Static method reference: • String::valueOf same as x -> String.valueOf(x)

• Non-static method reference: • Object::toString same as x -> x.toString()

• Capturing method reference: • x::toString same as () -> x.toString() • Constructor reference: • ArrayList::new same as () -> new ArrayList<>()

Page 8: Java 8

8

What Lambdas Cannot Do

• Non-Final Variable Capture – variables used in Lambdas cannot change (Lambdas are said to be "capturing" if they access a non-static variable or object that was defined outside of the lambda body. )

• Control Flow – cannot break out of a loop with an early return

• Cannot instantiate abstract classes using lambdas

Page 9: Java 8

9

Fundamental shift: from imperative to functional style

• imperative style - define step by step how to do things

• smells - mutating variables, external iterations

• declarative styles - let the API perform the operations

Page 10: Java 8

10

Commonly Useful Functional Interfaces

• Function<T, R> - take a T as input, return an R as ouput

• Predicate<T> - take a T as input, return a boolean as output

• Consumer<T> - take a T as input, perform some action and don't return anything

• Supplier<T> - with nothing as input, return a T• BinaryOperator<T> - take two T's as input, return

one T as output, useful for "reduce" operations

Page 11: Java 8

11

Streams

• The new java.util.stream package provides utilities "to support functional-style operations on streams of values"

• similar to an iterator• Can be sequential or running in parallel• Two operations:

• intermediate (ie. filter or map)• Terminal (ie. sum)

NoteL Intermediate operations are lazy, processing starts with a terminal operation

Page 12: Java 8

12

Stream Operation Properties

• Stateful - A stateful operation imposes some new property on the stream, such as uniqueness of elements, or a maximum number of elements, or ensuring that the elements are consumed in sorted fashion. These are typically more expensive than stateless intermediate operations.

• Short-circuiting - A short-circuiting operation potentially allows processing of a stream to stop early without examining all the elements. This is an especially desirable property when dealing with infinite streams; if none of the operations being invoked on a stream are short-circuiting, then the code may never terminate.

Page 13: Java 8

13

Intermediate Operations• filter- Exclude all elements that don't match a Predicate.• map - Perform a one-to-one transformation of elements using a Function.• flatMap - Transform each element into zero or more elements by way of

another Stream.• peek - Perform some action on each element as it is encountered. Primarily

useful for debugging.• distinct - Exclude all duplicate elements according to their .equals behavior.

This is a stateful operation.• sorted - Ensure that stream elements in subsequent operations are

encountered according to the order imposed by a Comparator. This is a stateful operation.

• limit - Ensure that subsequent operations only see up to a maximum number of elements. This is a stateful, short-circuiting operation.

• substream - Ensure that subsequent operations only see a range (by index) of elements. Like String.substring except for streams. There are two forms, one with a begin index and one with an end index as well. Both are stateful operations, and the form with an end index is also a short-circuiting operation.

Page 14: Java 8

14

Terminal Operations• forEach - Perform some action for each element in the stream.• toArray - Dump the elements in the stream to an array.• reduce - Combine the stream elements into one using a BinaryOperator.• collect - Dump the elements in the stream into some container, such as a

Collection or Map.• min - Find the minimum element of the stream according to a Comparator.• max - Find the maximum element of the stream according to a Comparator.• count - Find the number of elements in the stream.• anyMatch - Find out whether at least one of the elements in the stream matches a

Predicate. This is a short-circuiting operation.• allMatch - Find out whether every element in the stream matches a Predicate.

This is a short-circuiting operation.• noneMatch - Find out whether zero elements in the stream match a Predicate.

This is a short-circuiting operation.• findFirst - Find the first element in the stream. This is a short-circuiting operation.• findAny - Find any element in the stream, which may be cheaper than findFirst for

some streams. This is a short-circuiting operation.

Page 15: Java 8

15

Steps in using a Stream

1. Obtain a stream from some source.2. Perform one or more intermediate

operations.3. Perform one terminal operation.