What's new in Java 8

Andy Balaam
artificialworlds.net/blog

Contents

Functional, functional, functional

Java 8 brings features from functional languages to Java:

Lambdas & method refs

import static java.util.Collections.sort;
import static java.util.Arrays.asList;
// ...
List words = asList( "foo", "q", "ba" );
sort( words, (s1, s2) -> s1.length() - s2.length() );
System.out.println( words );

Lambdas & method refs

$ java SortList 
[q, ba, foo]

Lambdas & method refs

import static java.util.Comparator.comparingInt;
//...
List words = asList( "foo", "q", "ba" );
words.sort( comparingInt( String::length ) );
System.out.println( words );

Lambdas & method refs

Syntax:

import static java.util.function.*;
// ...
IntSupplier f1 = () -> 4 + 3;
IntFunction f2 = (x) -> x + 3;
IntBinaryOperator f3 = (x, y) -> x + y;

It's a magic arrow.

Lambdas & method refs

Why?

Lambdas & method refs

Why? - Convenience

JButton b = new JButton("Click!");
b.addActionListener(e -> b.setText("Clicked."));

Lambdas & method refs

Why? - Elegance

List words = asList( "foo", "q", "ba" );
words.forEach( System.out::println );

$ java ForEach 
foo
q
ba

Lambdas & method refs

Why? - Power

int x = Integer.intValue( args[0] );
three_state( x,
    () -> System.out.println( "zero" ),
    () -> System.out.println( "positive" ),
    () -> System.out.println( "negative" )
);

Lambdas & method refs

$ java ThreeState 2
positive
$ java ThreeState -2
negative
$ java ThreeState 0
zero

Optional

No more nulls!

Optional.ofNullable( map.get( key ) )
    .orElse( "MISSING" );

Streams

List words = asList( "foo", "q", "ba" );
String res = words.stream()
    .map( s -> "'" + s + "', " )
    .reduce( "", (a, b) -> a + b );
System.out.println( res );
$ java StreamNames 
'foo', 'q', 'ba', 

Streams

Stream.iterate(1, i -> i+1)
    .limit( 4 )
    .forEach( System.out::println );
$ java StreamTake 
1
2
3
4

Streams

Stream.iterate(1, i -> i+1)
    .limit( 7 )
    .filter( x -> x % 2 == 0 )
    .forEach( System.out::println );
$ java StreamFilter 
2
4
6

Streams

Default methods

@FunctionalInterface
public interface Iterable {
    default void forEach(Consumer<? super T> action) {
        for (T t : this) {
            action.accept(t);
        }
    }
}

Misc

Misc - JavaScript

$ jjs
jjs> false == '0'
true
jjs> false == ''
true
jjs> '0' == ''
false
jjs> "This has to be JavaScript"
This has to be JavaScript

The Good

The Bad

The Ugly

More info

Credit: leanpub.com/whatsnewinjava8

Donate! patreon.com/andybalaam
Play! Rabbit Escape
Videos youtube.com/user/ajbalaam
Twitter @andybalaam
Blog artificialworlds.net/blog
Projects artificialworlds.net