Java 8 brings features from functional languages to Java:
import static java.util.Collections.sort; import static java.util.Arrays.asList; // ... Listwords = asList( "foo", "q", "ba" ); sort( words, (s1, s2) -> s1.length() - s2.length() ); System.out.println( words );
$ java SortList [q, ba, foo]
import static java.util.Comparator.comparingInt; //... Listwords = asList( "foo", "q", "ba" ); words.sort( comparingInt( String::length ) ); System.out.println( words );
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.
Why?
Why? - Convenience
JButton b = new JButton("Click!");
b.addActionListener(e -> b.setText("Clicked."));
Why? - Elegance
Listwords = asList( "foo", "q", "ba" ); words.forEach( System.out::println );
$ java ForEach foo q ba
Why? - Power
int x = Integer.intValue( args[0] ); three_state( x, () -> System.out.println( "zero" ), () -> System.out.println( "positive" ), () -> System.out.println( "negative" ) );
$ java ThreeState 2 positive $ java ThreeState -2 negative $ java ThreeState 0 zero
No more nulls!
Optional.ofNullable( map.get( key ) ) .orElse( "MISSING" );
Listwords = 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',
Stream.iterate(1, i -> i+1)
.limit( 4 )
.forEach( System.out::println );
$ java StreamTake 1 2 3 4
Stream.iterate(1, i -> i+1)
.limit( 7 )
.filter( x -> x % 2 == 0 )
.forEach( System.out::println );
$ java StreamFilter 2 4 6
@FunctionalInterface public interface Iterable { default void forEach(Consumer<? super T> action) { for (T t : this) { action.accept(t); } } }
$ jjs jjs> false == '0' true jjs> false == '' true jjs> '0' == '' false jjs> "This has to be JavaScript" This has to be JavaScript
Credit: leanpub.com/whatsnewinjava8
Donate! | patreon.com/andybalaam |
---|---|
Play! | Rabbit Escape |
Videos | youtube.com/user/ajbalaam |
@andybalaam | |
Blog | artificialworlds.net/blog |
Projects | artificialworlds.net |