Skip to main content

Lambda Expression And Stream API Operations In Java




LAMBDA EXPRESSION:

              Lambda expression is the most advanced features of java and it introduced in java 8.It basically instance of the functional interface(which interface contain only one abstract method).In lambda expression,there is only abstract functions are implemented.functional interfaces are implement only one abstract method but it can contain any number of default and static method. Runnable and Comparable are the example of functional interface.


STREAM API:

          A stream is the sequence of processed data source which supports various operations such as filter, map, reduce, find, match etc. 
         In-stream the aggregate operations and the bulk operations processing convenient and fast.

             Before stream API, for a simple operation like comparing with a string with the element of a string array, we must iterate the total array and compare the String with each element of the array and get the result.
               In the above operation, the client program handles all the processing algorithm like iterating the array, comparing the String with the element etc so it is also an external iteration.
              To avoid external iterations and minimal use of code Stream API provide different functionality to take operation on data sources.



STREAM CREATION:

  
    //Initialize a list type of Integer
    List list=Arrays.asList(0,15,32,45,20,55,24,71);
  
    //Stream of Integer list
    Stream stream=list.stream();
  


  
     //List of type student class 
     List studentList = Arrays.asList(new Student(01,"student1",50),new Student(02,"student2",80),new Student(03,"student3",88));
   
    //Create a stream of StudentList
    Stream studentStream = studentList.stream();

    //Create stream of individual object of list  
    Stream  objectStream=Stream.of(studentList.get(0)).collect(Collectors.toList()));

     To create a stream of the collection we use the stream() of java.util.Collection interface.

STREAM API OPERATIONS:


             Java Stream API provide different operations on collections to process data and manipulate the algorithm of processing. These common operations are forEach, map,collect,filter,findFirst and so on.let's discuss some important operations.

1.Collect:
      Collect is use to collect the process result from stream.
  
     public static void streamCollect() {
  
          List studentList=Arrays.asList(new Student(01,"student1",100),new Student(02,"student2",200),new Student(03,"student3",100));
          List list=studentList.stream().filter(n->n.getMarks()==100).map(n->n.getName()).collect(Collectors.toList());
  
          System.out.println("Filtered List who secured 100 mark:"+list);
     }
  

2.For Each:
      forEach is use to iterate the collections and make operation on the elements of the collections.

  
     public static void streamForEachOperation() {
  
         //List of integer type
         List list=Arrays.asList(1,2,3,4,5,6,7,8,9);
  
         //initialize new list to store updated value
         List updateList=new ArrayList();

         //forEach operation using stream
         list.stream().forEach(n->{
            updateList.add(n+10);
         });
  
         System.out.println("After addition of 10,result list:"+updateList);
    }
  

3.Map:
      Using map in a minimal use of code we can process the element.


  
     public static void streamMapOperation() {
  
         //List of integer type
         List list=Arrays.asList(1,2,3,4,5,6,7,8,9);
 
         //update value using map 
         List    updateList=list.stream().map(n->n+10).collect(Collectors.toList());
  
         System.out.println("After addition of 10 using map,result list:"+updateList);
     }
  
4.Filter:
      This produces a new stream that contains elements of the original stream that pass a given test (specified by a Predicate).

  
     public static void streamFilter() {
  
           List studentList=Arrays.asList(new Student(01,"student1",100),new Student(02,"student2",200),new Student(03,"student3",100));
           List list=studentList.stream().filter(n->n.getMarks()==100).map(n->n.getName()).collect(Collectors.toList());
  
           System.out.println("Filtered List who secured 100 mark:"+list);
      }
  
5.Distinct:
      distinct() does not take any argument and returns the distinct elements in the stream, eliminating duplicates. It uses the equals() method of the elements to decide whether two elements are equal or not.

  
     public static void streamDistinct() {
  
           List list=Arrays.asList(2,5,3,4,2,1,8,1,6,3,5,4);
 
           List distinctIntList =   list.stream().distinct().collect(Collectors.toList());
  
           System.out.println("Distinct Array:"+distinctIntList);
     }
  
6.Sorted:
     Sorted() is Intermediate operations which return a stream of element with natural sequence of order. We can sort with manual order instead of natural order by using Comparator.

  
      public static void streamSorted() {
  
              List list= Arrays.asList("yogi","prem","ashish","sudhansu","akash","bijoy");
  
              List sortedListAsc = list.stream().sorted().collect(Collectors.toList());
  
              List sortedListDesc = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList()); 
  
              System.out.println("Sorted resultList asc:::"+sortedListAsc);
  
              System.out.println("Sort result list desc:::"+sortedListDesc);
      }
  
7.Match:
        Match work with collections, used to be check the predicate match with the stream. It's return Boolean value in result. Above methods are the some example of match operations.

  
     public static void streamMatch() {
  
            List list = Arrays.asList("Ashish","Prem","Akash","Bijoy","Raman");
  
            boolean anymatch = list.stream().anyMatch(l -> l.startsWith("A"));
  
            boolean allmatch = list.stream().allMatch(l -> l.startsWith("A"));
  
            boolean noneMatch = list.stream().noneMatch(l -> l.startsWith("A"));
  
            System.out.println("Any match:"+anymatch);
  
            System.out.println("All Match:"+allmatch);
  
            System.out.println("None Match:"+noneMatch);
  
      }
  
8.Count:
      Java count() allow to return count the filtered data. This is a terminal operation which return number of element filtered.

  
     public static void streamCount() {
            List list = Arrays.asList("Ashish","Prem","Akash","Bijoy","Raman");
  
             long count = list.stream().filter(n -> n.startsWith("A")).count();
  
             System.out.println("Count:"+count);
      }
  
9.Reduce:
       Reduce operation involves adding elements to a collection, then every time your accumulator function processes an element, it creates a new collection that includes the element, which is inefficient. Reduce() would be more efficient to update an existing collection.

  
     public static void streamReduce() {
  
              List list = Arrays.asList("Ashish","Prem","Akash","Bijoy","Raman");
  
              String result= list.stream().reduce((m,n) -> m+"-"+n).get();
  
              System.out.println("Reduce string:"+result);
      }
  

Comments

Popular posts from this blog

Send FTL In Email Using Spring Boot

                  In this topic, we discuss mail protocol and how to send email using mail library and how can we sent an email with more dynamic and with some more graphical interface and it's really looking good than the traditional email content. Here we use FTL to make email a more graphical experience. We try to show the example of this topic as possible as an easy way. so without wasting any time let's start the topic. WHAT IS FTL AND WHAT'S THE BENEFITS?          FTL(Free marker template) is a Java-based template language which is used to make the more dynamic and graphical experience on screen. FTL discovered by Apache foundation. It focuses on java based dynamic template design. Free marker template file extension is .ftl which is approx. as same as HTML code but the major difference is, we can send the data from Java source classes to show dynamic content. It's the main focus on MVC architecture which helps in separating web pages designer fro

QR Code Generate using zxing in spring boot

WHAT IS QR CODE AND HOW TO GENERATE QR CODE USING JAVA:           QR Code stands for Quick Response Code first design in Japan in 1994. The QR code is the trademark for a type of matrix barcode. The main purpose is to store information and is easily read by the advanced mobile system. The QR code is the two-dimensional bar code which store the piece of information.in the QR code information are encoded in 4 standardized encoding mode (numeric, alphanumeric, byte/binary, and kanji)    to store data efficiently. In Java, we can generate a QR code using zxing API provided by Google .zxing API support 4000 characters to encode. So without wasting any time let begin with an example for a better preference. PROJECT STRUCTURE: MAVEN DEPENDENCIES:        Put the dependencies on pom.xml pom.xml: <!-- https://mvnrepository.com/artifact/com.google.zxing/core --> <dependency>      <groupId>com.google.zxing

Scheduler(Task Executor) In Spring Boot

WHAT IS A SCHEDULER?       Firstly know about what is scheduling. Scheduling is a process that executing a task in a certain time period. A scheduler is a tool, the main objective is to implement the scheduling process. Mainly scheduler is used to perform the batch task for the repeated manner and perform the action of task without any outer other events. IMPLEMENTATION OF SCHEDULER IN SPRING BOOT:        In spring boot we can implement scheduler in multiple ways but here we use the annotation to implement the scheduler. In spring boot we can implement scheduler using @Scheduled annotation. The @Scheduled annotation internally uses the TaskScheduler interface to schedule a task. To enable the @Scheduled annotation we must use @EnableScheduling annotation in the Configuration file.        Let's start with an example of task scheduler. Her we use STS(spring tool suite) to build the spring boot project. First, build a project with web configuration. PROJECT S