Java Streams, Lambda Expression - Bug Reaper

                  Bug Reaper

Lean about Automation Testing,Selenium WebDriver,RestAssured,Appium,Jenkins,JAVA,API Automation,TestNG,Maven, Rest API, SOAP API,Linux,Maven,Security Testing,Interview Questions

Sunday 22 March 2020

Java Streams, Lambda Expression

Streams
We can perform various aggregate operations on the data returned from collections classes by reducing the complexity of the code.

Java 8 came with a major addition to the JDK collection framework, namely the stream API. Similar to collections, streams represent sequences of elements. Collections support operations such as add(), remove(), and contains() that work on a single element. Streams, in contrast, have bulk operations such as forEach(), filter(), map(), and reduce() that access all elements in a sequence

Lambda Expression
It introduce  a new operator-> into JAVA.    

It divides the lambda expression into 2 parts
Left side specifies the parameters required by the expression
Right side specifies the actions of the lambda expression

Streams are powerful they can scan whole collection parallely unlike in ArrayList we use for loop and then we scan using for loop sequentially from 0 to size of the list.

Streams work in three stages

1.)Create a stream
2.) Perform intermediate operation on initial stream to transform it into another stream to perform operations
3.) Perform terminal operations on the final stream to get results


Example

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamsPractice {
    public static void main(String[] args) {

        List<String> str = new ArrayList<>();

        str.add("Neeraj");
        str.add("ABC");
        str.add("XYZ");
        //Here Array List str is converted into streams, then filter, then variable s, then what action you need to perform
        str.stream().filter(s -> s.startsWith("A"));

        //Here s will scan the array parallely because of which speed is faster and s.startsWith("A") will give another stream on which we will put operation like count()
        long count = str.stream().filter(s -> s.startsWith("A")).count();

        long count1 = str.stream().filter(s -> s.contains("ABC")).count();


        System.out.println(count);
        System.out.println(count1);

        long count2 = Stream.of("Neeraj", "ABCD", "Hello").filter(s -> s.contains("ABCD")).count();
        System.out.println(count2);

        //Above stream can also be written like below
        long count3 = Stream.of("Neeraj", "ABCD", "Hello").filter(s ->
                {
                    s.contains("ABCD");
                    return false;
                }
        ).count();

        System.out.println(count3);

        //print all names whose lenght>2 now when we perform operation we will get s as output, and then we perform for Each
        str.stream().filter(s -> s.length() > 2).forEach(s -> System.out.println(s));

        //Here we will use limit to limit number of data
        str.stream().filter(s -> s.length() > 2).limit(1).forEach(s -> System.out.println(s));

        //Manipulate Streams

        str.stream().filter(s -> s.length() > 2).map(s -> s.toLowerCase()).forEach(s -> System.out.println(s));

        //here we are creating list directly no need to to add again and again
        List<String> namesinArrayList = Arrays.asList("Nakul", "saurabh", "Ankur");

        //sort and convert to lowercase
        namesinArrayList.stream().sorted().map(s -> s.toLowerCase()).forEach(s -> System.out.println(s));


        //Combine two arrayList

        Stream<String> newStream = Stream.concat(str.stream(), namesinArrayList.stream());

       // newStream.forEach(s -> System.out.println("here-->" + s));
        boolean flag=newStream.anyMatch(s->s.equalsIgnoreCase("Nakul"));

        System.out.println(flag);


    //Now we will convert List to Stream do some manipulation and then send back to a new List

        List<String> arrayList=namesinArrayList.stream().filter(s->s.equals("Nakul")).collect(Collectors.toList());

        System.out.println("here list through Streams"+arrayList);

        //print unique numbers from the array

        List<Integer> list=Arrays.asList(1,6,3,9,10,1);
        System.out.println("Sorted and unique-->");
        list.stream().distinct().sorted().forEach(s-> System.out.print(s));

    }
}



Output
1
1
1
0
Neeraj
ABC
XYZ
Neeraj
neeraj
abc
xyz
ankur
nakul
saurabh
true
here list through Streams[Nakul]
Sorted and unique-->
136910

No comments:

Post a Comment