Skip to main content

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

Comments

Popular posts from this blog

Access multiple Databases in JPA

According to JPA specification we can define multiple "persistence-unit" elements (i.e. like below) in persistence.xml file and can easily refer them inside Dao layers as this. public class PolarDaoImpl {     @PersistenceContext(unitName="PolarPU")     protected EntityManager entityManager; -- } public class BearDaoImpl {     @PersistenceContext(unitName="BearPU")     protected EntityManager entityManager; -- } Checkout sample persistence.xml <?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">     <!-- Database 1 -->     <persistence-unit name="PolarPU" transaction-type="RESOURCE_LOCAL">         <

JPA 2 new feature @ElementCollection explained

@ElementCollection is new annotation introduced in JPA 2.0, This will help us get rid of One-Many and Many-One shitty syntax. Example 1: Stores list of Strings in an Entity @Entity public class Users implements Serializable {     private static final long serialVersionUID = 1L;     @Id     @GeneratedValue(strategy = GenerationType.AUTO)     private Long id;     @ElementCollection     private List<String> certifications = new ArrayList <String> ();     public Long getId() {         return id;     }     public void setId(Long id) {         this.id = id;     }     public List <String> getCertifications() {         return certifications;     }     public void setCertifications(List <String> certifications) {         this.certifications = certifications;     } .. }         Users u = new Users();         u.getCertifications().add("Sun Certified Java Programmer");         em.persist(u); Generated Tables    Users    Co

Reuse JPA Entities as DTO

Note : Major design advantages of JPA Entities are they can detached and used across tiers and networks and later can by merged. Checkout this new way of querying entities in JPA 2.0 String ql = " SELECT new prepclass2.Employee (e.firstname, e.lastname) FROM Employee e "; List<Employee> dtos = em.createQuery(ql).getResultList(); The above query loads all Employee entities but with subset of data i.e. firstname, lastname. Employee entity looks like this. @Entity @Table(name="emp") public class Employee implements Serializable {     private static final long serialVersionUID = 1L;     @Id     @GeneratedValue(strategy = GenerationType.AUTO)     private Long id;     @Column     private String firstname;     @Column     private String lastname;     @Column     private String username;     @Column     private String street;     @Column     private String city;     @Column     private String state;     @Column     private String zipc