Thursday, July 3, 2014

Introduction to Java 8: Lambda Expressions and Streams

Lambda
- Ways of representing functions
- pre-built function building blocks
- Set of function composition methods

Streams
 - Wrappers around collections
 - map, reduce, filter, forEach
 - Lazy Evaluation
 - Can be made parallel

Note:
Lambda is not lisp
Stream is not Hadoop

Why Lambda's in Java
  Ability to pass functions around (Javascript, Lisp, Ruby, Scala etc)
  Functional approach proven concise, useful, and parallelizable

Java 7 version
String[] testStrings = {"", "", ""};
Arrays.sort(testStrings, new Comparator() {
   @Override
   public int compare(String s1, String s2) {
      return (s1.length() - s2.length());
   }
});

Lambda version
Arrays.sort(testStrings, (s1, s2) -> s1.length() - s2.length());

Lambda
 - replaces anonymous inner class' single method
 - No type should be used (Type inferencing)
 - Parens optional for single arg (Parens omitting)
     button.addActionListener(e -> setBg(Color.RED));
 - can refer to local, instance variable
 - are not allowed to modify local variables
 - allowed to modify instance variables
 - this is outer class

@FunctionalInterface
  - tells compiler is a functional interface
  - only one abstract method
  - other's won't be able to add more methods, compile time check

Method References
 - E.g., Math::cos or myVar::myMethod

java.util.functions

Streams
Stream methods
 forEach, map, filter, findFirst, findAny

how to make stream
 - Stream.of(val, val)
 - list.stream()
 - don't use int use wrappers Integer array

Array
  - strm.toArray(EntryType[]::new)
List
  - strm.collect(Collectors.toList())
String
  - strm.collect(Collectors.joining(delim)).toString()

E.g.,

String[] arr = {"a", "b", "c"};
        Stream.of(arr).parallel().forEach(System.out::println);

Double[] nums = {1.0, 2.0, 3.0, 4.0, 5.0};
        Double[] squars = Stream.of(nums).map(n -> n * n).toArray(Double[]::new);
        Stream.of(squars).forEach(System.out::println);

Double[] nums1 = {1.0, 2.0, 3.0, 4.0, 5.0};
        Double[] squars1 = Stream.of(nums).filter(n -> n % 2 == 0).toArray(Double[]::new);
        Stream.of(squars1).forEach(System.out::println);

Optional squars2 = Stream.of(nums).filter(n -> n % 2 == 0)
                .filter(n -> n > 10).findFirst();
        Stream.of(squars2).forEach(System.out::println);

System.out.println(Stream.of(arr).reduce("", String::concat));
System.out.println(Stream.of(nums).reduce(1.0, (n1, n2) -> n1 * n2));

comma, space delimiter.
StringJoiner j = new StringJoiner(", ");
j.add("").add("") etc

Limiting Stream Size
limit(n) - returns a Stream of first n elements
substream(n) - starts with nth element

Comparisons - sorted, min, max, distinct

- Sorting by salary
 empStream.map(..),filter(..).limit(..)
   .sorted( (e1, e2) -> e1.getSalary() - e2.getSalary())

- Richest employee
 empStream.map(..),filter(..).limit(..)
   .max( (e1, e2) -> e1.getSalary() - e2.getSalary()).get()

Checking Matches - allMatch, anyMatch, noneMatch

TODO
Predicate, Function & BiFunction, Consumer, Supplier and binaryOperator

1 comment:

John Alert said...

I have read your blog its very attractive and impressive. I like it your blog.

Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

Java Online Training Java Online Training Core Java 8 Training in Chennai java 8 online training JavaEE Training in Chennai Java EE Training in Chennai