Uses of java 8 lambda expressions in collections

Uses of java 8 lambda expressions in collections

Lambda expression facilitates functional programming, and simplifies the development a lot, Lambada provides the feature like sort of anonymous function which we use in the scripting language like PHP or Js which provide the inline implementation of the interface or generic operations which also avoid the need anonymous class

Basic syntax


(param) -> retrunValue;

when we have the single statement we do not need to specify the return value but when we have complex code we might modify the syntax like this

(param) -> {
 int a = parm +1;
 retun a;
}  

So param will the type of the element of which is declared in interface or collection or maps and return type could be same or varied based on the collection type we use.

We can avoid most of the boilerplate code using lambda expression few of the generic use cases which I have used to in day to day activities in my programming are charted down below with basic beginner examples

Finding a value or values with in the list using

By using lambda function we can avoid most of the lines like a loop, if condition and temp variable and make code readable as shown in the basic example.

List<Int> a = new ArrayList<>();
a.add(1);
a.add(250) .....;
//finding a value
int test = a.stream().filter(ele->ele ==2).findFirst().orElse(0);
//finding a values
List test2 = a.stream().filter(ele -> (ele == 2 || ele == 3).findAll().collect(collector.toList());

Modify and collect to different list

We can modify the list of element list converting to float or calculating the required value using the value just by using map() function and writing an expression which we need to calculate.basic example show to calculate the square root of array elements

List<Int> a = new ArrayList<>();
a.add(1);
a.add(250) .....;
//finding the square root of a arrays
List<int> test = a.stream().map(ele - > ele * ele).collect(collector.toList());
//having one or more computational statement
List<int> test = a.stream().map(ele - > {int sqrt = ele * ele;return sqrt/10}).collect(collector.toList());

Group by function

The groupBy() function is very useful like we need to group certain value based on name or some small condition, so collector() of grouping will always be a map type of define collection of the source basic example shows how to group by even or odd numbers

List<Int> a = new ArrayList<>();
a.add(1);
a.add(250) .....;
//group by even and odd number
Map<String,List<Int> test = a.stream().collect(Collectors.groupingBy(x -> (x % 2)== 0 ? "even" : "odd"));

Iteration or looping

The simplified or a readable for loop can be written by using lambda function which works as an iterator.

List<Int> a = new ArrayList<>();
a.add(1);
a.add(250) .....;

a.forEach(ele -> System.out.println(ele));

Get the complete Summary of Collection Elements

The summarizingInt() is the function gives basic details like count, sum, min, average, max in map output.

List<Int> a = new ArrayList<>();
a.add(1);
a.add(250) .....;
System.out.println(a.stream().collect(Collectors.summarizingInt(p->p))));

Removing a duplicates from the array

As we know in Java's equals() function defined for all objects so which helps to check unique values by hashcode or by value in some instances, And we also know set collection will not allow the duplicate so we can use this to filter out duplicates by writing a lambda function as shown below.

List<Int> a = new ArrayList<>();
a.add(1);
a.add(250) .....;
Set nonDuplicates = a.stream().collect(Collectors.toSet());

Example of Reduce function

Reduce function will provide previous object i.e returned or the first element of the list and next element, so we can write simple programs like concatenating, summation or multiplication.

List<Int> a = new ArrayList<>();
a.add(1);
a.add(250) .....;
// this function convert nubers from array to string as comma seperated value 
String numberAsString = a.stram().reduce((ele1,ele2) - > ele1 +","+ ele2);

Convert comma separated value to List

List<String> test =  Arrays.asList("1,2,3,5".split(","))