overview lambda streams

Post on 08-Sep-2014

2.225 Views

Category:

Technology

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

This presentation was created by Stuart Marks and was used at Japanese JUG event (JJUG CCC) at 5/15(Sun).

TRANSCRIPT

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 1

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 2

The following is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle.

Overview of Java 8 Lambda and Streams Stuart W. Marks Principal Member of Technical Staff

Twitter: @stuartmarks

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 4

What is a Lambda?

 A lambda is a function.

 A function is a computation that takes parameters and returns a value.

 Until Java 8, functions could only be implemented using methods.

 A lambda enables functions to be passed around or stored like data.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 5

Example: Sorting a List of Objects

class Person { String name; int age; String getName() { return name; } int getAge() { return age; } } List<Person> list = ... ; Collections.sort(list, ??? );

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 6

Example: Sorting a List of Objects

List<Person> list = ... ; public int compare(Person p1, Person p2) { return p1.getName().compareTo(p2.getName()); } Collections.sort(list, ??? );

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 7

Example: Sorting a List of Objects

List<Person> list = ... ; class ComparePersonsByName implements Comparator<Person> { @Override public int compare(Person p1, Person p2) { return p1.getName().compareTo(p2.getName()); } } Collections.sort(list, ??? );

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 8

Example: Sorting a List of Objects

List<Person> list = ... ; class ComparePersonsByName implements Comparator<Person> { @Override public int compare(Person p1, Person p2) { return p1.getName().compareTo(p2.getName()); } } Collections.sort(list, new ComparePersonsByName());

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 9

Example: Sorting a List of Objects

List<Person> list = ... ; Collections.sort(list, new Comparator<Person>() { @Override public int compare(Person p1, Person p2) { return p1.getName().compareTo(p2.getName()); } });

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 10

Example: Sorting a List of Objects

List<Person> list = ... ; Collections.sort(list, (Person p1, Person p2) { return p1.getName().compareTo(p2.getName()); } );

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 11

Example: Sorting a List of Objects

List<Person> list = ... ; Collections.sort(list, (Person p1, Person p2) -> p1.getName().compareTo(p2.getName()) );

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 12

Example: Sorting a List of Objects

List<Person> list = ... ; Collections.sort(list, (p1, p2) -> p1.getName().compareTo(p2.getName()) );

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 13

Functional Interfaces

interface Runnable { public void run(); } new Thread(new Runnable() { @Override public void run() { System.out.println("Hello, thread!"); } }); new Thread(() -> System.out.println("Hello, thread!"));

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 14

New APIs Using Functional Interfaces

List<Person> list = ... ; for (Person p : list) { System.out.println(p); } list.forEach(p -> System.out.println(p));

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 15

New APIs Using Functional Interfaces

List<Person> list = Collections.synchronizedList(...); for (Person p : list) { System.out.println(p); } list.forEach(p -> System.out.println(p));

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 16

New APIs Using Functional Interfaces

List<Person> list = ... ; for (Person p : list) { if ("Jones".equals(p.getName())) { ??? how to remove this Person ??? } }

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 17

New APIs Using Functional Interfaces

List<Person> list = ... ; for (Iterator<Person> iter = list.iterator(); iter.hasNext(); ) { Person p = iter.next(); if ("Jones".equals(p.getName())) { iter.remove(); } } list.removeIf(p -> "Jones".equals(p.getName()));

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 18

New APIs Using Functional Interfaces

List<String> list = Arrays.asList("Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf"); for (ListIterator<String> iter = list.listIterator(); iter.hasNext(); ) { iter.set(iter.next().toUpperCase()); } list.replaceAll(s -> s.toUpperCase()); list.replaceall(String::toUpperCase); // method reference

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 19

Default Methods Added to Collections

Iterable.forEach(lambda) Collection.removeIf(lambda) List.replaceAll(lambda) List.sort(lambda) // replaces static method Collections.sort()

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 20

Default Methods Added to Collections

Collections.sort(list, (p1, p2) -> p1.getName().compareTo(p2.getName()) ); list.sort( (p1, p2) -> p1.getName().compareTo(p2.getName()));

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 21

Combining Operations

 New collection operations include forEach, removeIf, replaceAll  Each operates on a collection, possibly modifying it  What if we want to combine these operations?

–  for example, operate only certain elements that meet some criterion  Using collections, we'd need to copy and create temporary collections  Solution: streams

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 22

Streams

 Streams: a multiplicity of values –  no storage –  might or might not be ordered –  sort-of like an iterator –  affords serial or parallel processing

 Stream pipeline: –  a source –  zero or more intermediate operations –  a terminal operation

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 23

Streams

 Sources –  collections, array, varargs parameters, numeric range, lines of file

  Intermediate operations –  filter, map, distinct, sorted, skip, limit, flatMap

 Terminal operations –  forEach, toArray, collect, reduce, count, min, max –  findFirst, findAny, anyMatch, allMatch, noneMatch

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 24

Streams Example

// Given a list of persons, generate a sorted list of // names that longer than longer than 3 characters. List<Person> persons = ... ; persons.stream() .map(p -> p.getName()) .filter(s -> s.codePointCount(0, s.length()) > 3) .sorted() .forEach(s -> System.out.println(s));

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 25

Streams Example

// Given a list of persons, generate a sorted list of // names that longer than longer than 3 characters. List<Person> persons = ... ; persons.stream() .map(p -> p.getName()) .filter(s -> s.codePointCount(0, s.length()) > 3) .sorted() .forEach(System.out::println);

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 26

Streams Example

// Given a list of persons, generate a sorted list of // names that longer than longer than 3 characters. List<Person> persons = ... ; List<String> sortedNames = persons.stream() .map(p -> p.getName()) .filter(s -> s.codePointCount(0, s.length()) > 3) .sorted() .collect(Collectors.toList());

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 27

Streams Example

// Calculate pi using the Taylor Series // pi = 4 * (1 – 1/3 + 1/5 – 1/7 + ...) System.out.println( LongStream.range(0L, 1_000_000_000L) .map(i -> ((i & 1) == 0 ? 1 : -1) * (2 * i + 1)) .mapToDouble(i -> 4.0 / i) .sum());

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 28

Streams Example

// Calculate pi using the Taylor Series // pi = 4 * (1 – 1/3 + 1/5 – 1/7 + ...) System.out.println( LongStream.range(0L, 1_000_000_000L) .parallel() .map(i -> ((i & 1) == 0 ? 1 : -1) * (2 * i + 1)) .mapToDouble(i -> 4.0 / i) .sum());

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 29

Summary

 Lambdas: anonymous functions  Default methods  Method references  Streams: allow pipelined operations on multiple values

–  programmed using lambda –  enable parallelism

Lambdas and streams make code read more like the problem statement, resulting in code that is clear, concise, and easy to maintain.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 30

Java 8 Resources

 Download: java.oracle.com  Documentation & Tutorials: docs.oracle.com/javase  Source code: openjdk.java.net/projects/jdk8  FAQ: lambdafaq.org  Technical documents: openjdk.java.net/projects/lambda

–  State of the Lambda –  State of the Lambda: Libraries Edition

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 31

The preceding is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle.

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 32

top related