Java Stream API

Introduction to Java Stream API

Java Stream API was introduced as a new package –  ‘java.util.stream’ in Java 8 release. java.util.stream package consists of  interface , classes and enums. You can use stream API by importing java.util.stream package in your program.

This package basically supports functional-style operations on elements or we can say stream-of-elements. We will further elaborate this below.

A stream in Java is defined as a sequence of objects that supports many methods that can be pipelined to produce the desired result. Java 8 Stream API is  basically used to process collections of objects.

Java Stream keeps the ordering of the data same as it is in the source.

Java streams can be used to filter, collect, print, and convert from one data structure to another etc.

Features of Java Stream API

The features of Java stream are –

  • Java stream is not considered as a data structure as it does not store any element instead it takes input from the Collections, Arrays etc .
  • Java Streams never change the original data structure (provided as input), it only gives the result as per the pipelined methods.
  • Java Stream is considered to be functional in nature as operations performed on a stream never leads to modification in it’s source. For example, If a filter operation is performed on a Stream obtained from a collection , it will generate a new Stream haing filtered elements. It will not remove the elements from the original collection.
  • All operations on Java Stream is lazily executed means the code will only evaluate when required.
  • All the elements of a stream are visited once during the life of a stream. Same as an Iterator, a new stream should be generated to revisit the same elements of the source.

There are two types of operations can be executed on Stream –

  • Intermediate Operations : Each intermediate operation in Stream is lazily executed and it will return a stream as output, due to lazy loading, various intermediate operations can be pipelined.
  • Terminal Operations : These operations mark the end of the stream and it returns the result.

Java Streams vs Collection

Java Stream API

Operations on Java Streams

Intermediate Operations on Java Streams:

map: 

The map method in Java Streams is used for mapping the items in the collection to another objects as per the Function passed as argument. See example below :

List num = Arrays.asList(1,3,2,4,6,5);
List output = num.stream().map(a->a*a).collect(Collectors.toList());

filter:

The filter method in Java Streams is used to select elements from the Collection according to the Predicate passed as argument. See example below :

List items = Arrays.asList("Sugar","Lemon","Lime");
List output = items.stream().filter(a->a.startsWith("L")).collect(Collectors.toList());

sorted:

The sorted method in Java Streams is used to sort the provided stream. See example below :

List items = Arrays.asList("Sugar","Lemon","Lime","Almonds");
List output = items.stream().sorted().collect(Collectors.toList());

Terminal Operations on Java Streams:

collect:

The collect method in Java Streams is used to provide the result of the intermediate operation performed on the stream. See example below :

List num = Arrays.asList(1,2,6,3,5,4,1,5,2,3);
Set output = num.stream().map(a->a*a).collect(Collectors.toSet());

forEach:

The forEach method in Java Streams is used to iterate through each element of the stream. See example below :

List num = Arrays.asList(1,2,3,4,5,6);
num.stream().map(a->a*a).forEach(b->System.out.println(b));

reduce:

The reduce method in Java Streams is used to reduce the elements of a stream to just a single value.
This method takes  BinaryOperator as an arguement. See example below :

List num = Arrays.asList(6,2,3,4,5);
int output = num.stream().filter(a->a%2==0).reduce(0,(ans,i)-> ans+i);

Note : ans variable is assigned 0 as the initial value and i is added to it .

Java Stream Example: How to Filter Collection by using Stream

Below example illustrates following :

  1. Use of filter method on Java stream.
  2. Use of map method on Java stream.
  3. Use of collect method on Java stream.
import java.util.*; 
import java.util.stream.Collectors;

class Employee{ 
int empId; 
String empName; 
float salary; 
public Employee(int empId, String empName, float salary) { 
this.empId = empId; 
this.empName = empName; 
this.salary = salary; 
} 
} 

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

List<Employee> emp = new ArrayList<Employee>(); 


emp.add(new Employee(1,"John",45000f)); 
emp.add(new Employee(2,"Dina",30000f)); 
emp.add(new Employee(3,"Ross",20000f)); 
emp.add(new Employee(4,"Rachel",25000f)); 
emp.add(new Employee(5,"Chandler",70000f)); 

//Below function will return the employees whose salary is greater than 30000

List<Float> empFilteredList =emp.stream() 
.filter(e -> e.salary > 30000)// filtering data 
.map(e->e.salary) // fetching price 
.collect(Collectors.toList()); // collecting as list 

System.out.println(empFilteredList); 
} 
}

Output :

[45000.0, 70000.0]

Java Stream Example: How to Filter and Iterate Collection by using Stream

Below example illustrates following :

  1. Use of filter method on Java stream.
  2. Use of forEach method on Java stream.
import java.util.*; 
import java.util.stream.Collectors;

class Employee{ 
int empId; 
String empName; 
float salary; 
public Employee(int empId, String empName, float salary) { 
this.empId = empId; 
this.empName = empName; 
this.salary = salary; 
} 
} 
public class Example { 
public static void main(String[] args) { 

List<Employee> emp = new ArrayList<Employee>(); 

emp.add(new Employee(1,"John",45000f)); 
emp.add(new Employee(2,"Dina",30000f)); 
emp.add(new Employee(3,"Ross",20000f)); 
emp.add(new Employee(4,"Rachel",25000f)); 
emp.add(new Employee(5,"Chandler",70000f)); 

emp.stream() 
.filter(e -> e.salary > 30000)    // filtering data 
.forEach(e -> System.out.println(e.empName));   //iterating data

} 
}

Output :

John
Chandler

Java Stream Example: How to convert List into Map by using Stream

Below example illustrates following :

  1. Use of toMap method on Java stream.
import java.util.*; 
import java.util.stream.Collectors;

class Employee{ 
int empId; 
String empName; 
float salary; 
public Employee(int empId, String empName, float salary) { 
this.empId = empId; 
this.empName = empName; 
this.salary = salary; 
} 
} 
public class Example { 
public static void main(String[] args) { 

List<Employee> emp = new ArrayList<Employee>(); 

emp.add(new Employee(1,"John",45000f)); 
emp.add(new Employee(2,"Dina",30000f)); 
emp.add(new Employee(3,"Ross",20000f)); 
emp.add(new Employee(4,"Rachel",25000f)); 
emp.add(new Employee(5,"Chandler",70000f)); 

// Converting Employee List into a Map 
Map<Integer,String> empSalaryMap = 
emp.stream() 
.collect(Collectors.toMap(e->e.empId, e->e.empName));


System.out.println(empSalaryMap); 
} 
}

Output : 

{1=John, 2=Dina, 3=Ross, 4=Rachel, 5=Chandler}

Java Stream Example: How to convert List into Set by using Stream

Below example illustrates following :

  1. Use of toSet method on Java stream.
import java.util.*; 
import java.util.stream.Collectors;

class Employee{ 
int empId; 
String empName; 
float salary; 
public Employee(int empId, String empName, float salary) { 
this.empId = empId; 
this.empName = empName; 
this.salary = salary; 
} 
} 
public class Example { 
public static void main(String[] args) { 

List<Employee> emp = new ArrayList<Employee>(); 

emp.add(new Employee(1,"John",45000f)); 
emp.add(new Employee(2,"Dina",30000f)); 
emp.add(new Employee(3,"Ross",20000f)); 
emp.add(new Employee(4,"Rachel",55000f)); 
emp.add(new Employee(5,"Chandler",45000f)); 

// Converting Employee List into a Set 

Set<Float> empSalSet = 
emp.stream() 
.filter(e->e.salary > 30000) 
.map(e->e.salary) 
.collect(Collectors.toSet()); // collect it as Set(remove duplicate elements) 


System.out.println(empSalSet); 
} 
}

Output : 

[55000.0, 45000.0]

Java Stream Example: How to perform sum operation using Stream

Below example illustrates following :

  1. Use of summingDouble method on Java stream.
import java.util.*; 
import java.util.stream.Collectors;

class Employee{ 
int empId; 
String empName; 
float salary; 
public Employee(int empId, String empName, float salary) { 
this.empId = empId; 
this.empName = empName; 
this.salary = salary; 
} 
} 
public class Example { 
public static void main(String[] args) { 

List<Employee> emp = new ArrayList<Employee>(); 

emp.add(new Employee(1,"John",45000f)); 
emp.add(new Employee(2,"Dina",30000f)); 
emp.add(new Employee(3,"Ross",20000f)); 
emp.add(new Employee(4,"Rachel",55000f)); 
emp.add(new Employee(5,"Chandler",45000f)); 



// Using Collectors's method to sum the salary of employees. 
double salaryTotal = emp.stream() 
.collect(Collectors.summingDouble(e->e.salary)); 


System.out.println(salaryTotal); 
} 
}

Output : 

195000.0

Java Stream Example: How to find min and max number using Stream

Below example illustrates following :

  1. Use of max method on Java stream.
import java.util.*; 
import java.util.stream.Collectors;

class Employee{ 
int empId; 
String empName; 
float salary; 
public Employee(int empId, String empName, float salary) { 
this.empId = empId; 
this.empName = empName; 
this.salary = salary; 
} 
} 
public class Example { 
public static void main(String[] args) { 

List<Employee> emp = new ArrayList<Employee>(); 

emp.add(new Employee(1,"John",45000f)); 
emp.add(new Employee(2,"Dina",30000f)); 
emp.add(new Employee(3,"Ross",20000f)); 
emp.add(new Employee(4,"Rachel",55000f)); 
emp.add(new Employee(5,"Chandler",45000f)); 



// max() method to get max Employee Salary 
Employee empObject1 = emp.stream() 
.max((emp1, emp2)-> 
emp1.salary > emp2.salary ? 1: -1).get(); 

System.out.println(empObject1.salary); 


// min() method to get min Employee Salary 
Employee empObject2 = emp.stream() 
.max((emp1, emp2)-> 
emp1.salary < emp2.salary ? 1: -1).get(); 
System.out.println(empObject2.salary); 
} 
}

Output : 

55000.0
20000.0

Conclusion

That’s all folks! In this article, you have got the complete overview of Java 8 Streams API , its various operations and methods , its illustrative examples and difference between Java Stream and Collection.

Newsletter Updates

Enter your name and email address below to subscribe to our newsletter

Leave a Reply