Tuesday, 6 October 2020

How to use Stream API In Java

Stream API :- Stream API introduce is java version 8 . Stream is sequence of elements of that supports data processing operations .

Stream is use for performs data processing operations on java collection class like ArrayList ,LinkList;

How to use Stream ? 

To Working with Stream API involves three parts .

1. Data source (such as a collection like ArrayList ,LinkList)
2. Intermediate Operation to form stream data processing operations pipeline
3. Terminal Operation that execute the stream pipeline and produce the result .

Stream Intermediate Operation

Filter :-   Filter is predicate that return stream  of element  that filter predicate test method.
Map   :-  Map is function that map that takes one object T type and map to R Type 
               Object and return stream of R type object
Limit  :-  Limit is simple method that takes an Integer as argument that use 
                filter top number of element equal to given Integer and return Stream for those element.
Sorted :- Sorted is used to sort stream element in ascending and descending element
Distinct :-Distinct is use remove duplicate element from Stream 


Stream Terminal Operation

forEach :- ForEach is takes a Consumer as each element of Stream and apply 
                 Consumer interface accept method each element of stream . 
count   :-  Count return number of element present in stream .count return type is long.
collect :-   Collect is reduce stream and create new create collection of stream element .
skip   :-    Skip nth element from stream


Some Basic Stream operation

Operation Name                

Type 

Return Type

Argument of the operation

filter 

Intermediate 

Stream<T>

Predicate<T>

map 

Intermediate 

Stream<R>

Function<T,R>

limit 

Intermediate 

Stream<T>


sorted

Intermediate 

Stream<T>

Comparator<T> 

distinct 

Intermediate 

Stream<T>


skip 

Intermediate 

Stream<T>


forEach 

Terminal 

void


count 

Terminal 

long


anyMatch 

Terminal 

boolean


allMatch 

Terminal 

boolean


noneMatch 

Terminal 

boolean


findAny 

Terminal 

Optional<T>


findFirst 

Terminal 

Optional<T>


reduce 

Terminal 

Optional<T>


collect 

Terminal 

decide on based on collection type like List,Set,Map



 
Way to Build stream  by Stream Interface

 
 Stream<String> names = Stream.of("J K","Johny ","John");
 
 Integer[] numbers = {1,2,3,4,5,6,7,8,9,10};
 Stream<Integer> numberStream = Stream.of(numbers);

Stream Java Application

StreamApplication.java
s
package in.jk.java8.stream;

import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import in.jk.java8.Employee;

public class StreamApplication {

public static void main(String[] args) {

System.out.println("      Stream API Application ...\n");
List<Employee> employeeList = Employee.getEmployeeList();
System.out.println("Use of filter and map ...\n");

employeeList.stream()
                    .filter(employee -> employee.getEmpId() > 4)
                    .map(Employee::getName)
            .forEach(System.out::println);
System.out.println(" Use of Limit funtion\n");

employeeList.stream()
                    .filter(employee -> employee.getEmpId() > 4)
                    .map(Employee::getName)
                    .limit(2)
            .forEach(System.out::println);
System.out.println(" Use of distinct,count funtion/n");
long count1 = employeeList.stream()
                .filter(employee -> employee.getEmpId() > 1)
                .map(Employee::getName)
                .count();
System.out.println("Employee Count of Before distinct "+count1);
        long count2 = employeeList.stream()
                    .filter(employee -> employee.getEmpId() > 1)
                    .map(Employee::getName)
                    .distinct()
                    .count();
System.out.println("Employee Count of after distinct "+count2);
System.out.println("Employee names of after distinct ");
employeeList.stream()
                             .filter(employee -> employee.getEmpId() > 1)
                             .map(Employee::getName)
                             .distinct()
                             .forEach(System.out::println);
        System.out.println(" Use of collect()  funtion/n");
  employeeList.stream()
                .filter(employee -> employee.getEmpId() > 4)
                .map(Employee::getName)
                .collect(Collectors.toList())
                .forEach(System.out::println);

System.out.println(" Use of sorted() before map operation funtion\n");
employeeList.stream()
           .filter(employee -> employee.getEmpId() > 4)
           .sorted(Comparator.comparing(Employee::getName))
           .map(Employee::getName)
           .collect(Collectors.toList())
           .forEach(System.out::println);
 
 
System.out.println(" Use of sorted() after map operation funtion\n");
employeeList.stream()
           .filter(employee -> employee.getEmpId() > 4)
           .map(Employee::getName)
           .sorted(String::compareTo)
           .collect(Collectors.toList())
           .forEach(System.out::println);
 
System.out.println(" Use of skip(int n)  operation/n");
employeeList.stream()
       .skip(2)
           .map(Employee::getName)
           .collect(Collectors.toList())
           .forEach(System.out::println);
 
System.out.println(" Use of skip(int n)  operation\n");
boolean anyMatch= employeeList.stream()
       
           .map(Employee::getName)
           .anyMatch(name->name.equals("J K"));
System.out.println("Any Match "+anyMatch);
boolean allMatch= employeeList.stream()
      
           .map(Employee::getName)
           .allMatch(name->name.equals("J K"));
System.out.println("All Match "+allMatch);
boolean noneMatch= employeeList.stream()
      
           .map(Employee::getName)
           .noneMatch(name->name.equals("J K"));
System.out.println("Non Match "+noneMatch);
Optional<String> findName= employeeList.stream()
      
           .map(Employee::getName)
           .findAny();
System.out.println("Name  by findyAny \n"+findName.get());
Optional<String> findFirstName= employeeList.stream()
      
           .map(Employee::getName)
           .findAny();
System.out.println("Name by findyFirst \n"+findFirstName.get());
 
 
}

}

Employee.java

package in.jk.java8;

import java.util.ArrayList;
import java.util.List;

public class Employee {
private int empId;
private String name;
private String company;
private int salary;
//Getters and Setters
@Override
public String toString() {
return "Employee [empId=" + empId + ", name=" + name + ", company=" + company + ", salary=" + salary + "]";
}
public static  List<Employee>getEmployeeList() {
List<Employee> empList =new ArrayList<Employee>();
Employee  employee = new Employee();
        employee.setEmpId(1);
        employee.setName("J K");
        employee.setCompany("Google");
        employee.setSalary(1000);
        
        Employee  employee1 = new Employee();
        employee1.setEmpId(2);
        employee1.setName("J K");
        employee1.setCompany("Google");
        employee1.setSalary(2000);
        
        Employee  employee2 = new Employee();
        employee2.setEmpId(3);
        employee2.setName("J K");
        employee2.setCompany("Google");
        employee2.setSalary(3000);
        
        Employee  employee3 = new Employee();
        employee3.setEmpId(4);
        employee3.setName("SHA");
        employee3.setCompany("APAR");
        employee3.setSalary(4000);
        
        Employee  employee4 = new Employee();
        employee4.setEmpId(5);
        employee4.setName("HM");
        employee4.setCompany("PAYTM");
        employee4.setSalary(5000);
        
        Employee  employee5 = new Employee();
        employee5.setEmpId(5);
        employee5.setName("HM");
        employee5.setCompany("APAR");
        employee5.setSalary(6000);
        
        Employee  employee6 = new Employee();
        employee6.setEmpId(6);
        employee6.setName("JK");
        employee6.setCompany("APAR");
        employee6.setSalary(7000);
        
        Employee  employee7 = new Employee();
        employee7.setEmpId(7);
        employee7.setName("JK");
        employee7.setCompany("JET BRAINS");
        employee7.setSalary(8000);
        
        Employee  employee8 = new Employee();
        employee8.setEmpId(8);
        employee8.setName("AJ");
        employee8.setCompany("APAR");
        employee8.setSalary(9000);
        
        Employee  employee9 = new Employee();
        employee9.setEmpId(8);
        employee9.setName("AJ");
        employee9.setCompany("ADOBE");
        employee9.setSalary(10000);
        
        empList.add(employee);
        empList.add(employee1);
        empList.add(employee2);
        empList.add(employee3);
        empList.add(employee4);
        empList.add(employee5);
        empList.add(employee6);
        empList.add(employee7);
        empList.add(employee8);
        empList.add(employee9);
return empList;
}
}

Output in console ...

      Stream API Application ...

Use of filter and map ...

HM
HM
JK
JK
AJ
AJ
 Use of Limit funtion

HM
HM
 Use of distinct,count funtion/n
Employee Count of Before distinct 9
Employee Count of after distinct 5
Employee names of after distinct 
J K
SHA
HM
JK
AJ
 Use of collect()  funtion/n
HM
HM
JK
JK
AJ
AJ
 Use of sorted() before map operation funtion

AJ
AJ
HM
HM
JK
JK
 Use of sorted() after map operation funtion

AJ
AJ
HM
HM
JK
JK
 Use of skip(int n)  operation/n
J K
SHA
HM
HM
JK
JK
AJ
AJ
 Use of skip(int n)  operation

Any Match true
All Match false
Non Match false
Name  by findyAny 
J K
Name by findyFirst 
J K



No comments:

Post a Comment