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

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

Validating CSV Files

What is CsvValidator ?   A Java framework which validates any CSV files something similar to XML validation using XSD. Why should I use this ?   You don't have to use this and in fact its easy to write something your own and also checkout its source code for reference. Why did I write this ?   Some of our projects integrate with third party application which exchanges information in CSV files so I thought of writing a generic validator which can be hooked in multiple projects or can be used by QA for integration testing. What is the license clause ?   GNU GPL v2 Are there any JUnit test cases for me checkout ?  Yes,  source How to integrate in my existing project ? Just add the Jar which can be downloaded from here  CsvValidator.jar  and you are good. Instantiate  CsvValidator c onstructor which takes these 3 arguements          // filename is the the file to be validated and here is a  sample         // list - defines all the fields in the above csv file ( a