Wednesday, May 27, 2020

Lambda Expressions & Streams - Data Manipulation - Learning 3

In any SQL statement, 'where' condition is always referred to as "Predicate". Predicate is a function in java to apply a filter on it. 

Introduced in Java 1.8, Predicate is a function or interface which has a method that returns boolean. It has got other logical methods like 'and', 'or', 'negate', 'isEquals'. Here our point of interest will be the 'test' method which returns boolean. The method 'test' will be applied with Lambda Expression.


import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

public class FilterFramework {

public static <T> List<T> filter(List<T> items, Predicate<T> p) {
List<T> resultList = new ArrayList<T>();
for (T t : items) {// <-------------- This can be re-written 
if (p.test(t)) {// <------------- to implement stream 
                      //<-------------instead of Iterating
resultList.add(t);
}
}
return resultList;
}
}

Predicate's test method will execute the supplied Lambda Expression and items are filtered in the resultList. T can be any Object (Eg, Employee, Cat, Dog)

Reading and Writing JSON to a file

Why GSON? Nowadays JSON is more frequently used for data representation. There are a lot of libraries to convert java objects into JSO...