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">        ...

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 ...
               Top 10 Apps missing in HP TouchPad Without these Apps my experience is only limited to browsing web pages, though WebOS is really better multitasking device than iOS but without commonly used Apps it's only limited. 1. Native YouTube App   - You can't just use finger to do everything on 60% YouTube.com                       2. Netflix - I love to do multitasking, with Netflix running and ability to do other stuff     3 Facebook - Most of the people always like to be connected all the time here   My Mistake Skype Video is working     4  Skype - Ability to do voice and video chat, and without this I need to keep my Mac on.   5 Google Talk - Ability to do voice, video chat...