Java 8 Stream

Java provides a new additional package in Java 8 called java.util.stream.By using streams we can perform various aggregate operations on the data returned from collections, arrays, Input/Output operations.

Stream provides following features:

  • Stream does not store elements. It simply conveys elements from a source such as a data structure, an array, or an I/O channel, through a pipeline of computational operations.
  • Stream is functional in nature. Operations performed on a stream does not modify it’s source. For example, filtering a Stream obtained from a collection produces a new Stream without the filtered elements, rather than removing elements from the source collection.
  • Stream is lazy and evaluates code only when required.
  • The elements of a stream are only visited once during the life of a stream. Like an Iterator, a new stream must be generated to revisit the same elements of the source.

You can use stream to filter, collect, print, and convert from one data structure to other etc.

Let us look into some of the examples:

Filtering Collection with/without using Stream

package com.java.stream;

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

public class FilterWithoutSream {
public static void main(String[] args) {
List names = new ArrayList();
names.add(“Gyan”);
names.add(“Praveen”);
names.add(“Vivek”);
names.add(“Rochit”);

List filteredNames = new ArrayList<>();

for (String name : names) {
if (name.length() < 6) {
filteredNames.add(name);
}
}

System.out.println(“filteredNames:” + filteredNames);

}
}

Output:filteredNames:[Gyan, Vivek]

package com.java.stream;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class FilterWithStream{
public static void main(String[] args) {
List names = new ArrayList();
names.add(“Gyan”);
names.add(“Praveen”);
names.add(“Vivek”);
names.add(“Rochit”);

List filteredNames = names.stream().filter(str->str.length()<6).collect(Collectors.toList());
System.out.println(“filteredNames:”+filteredNames);

}
}

Output:filteredNames:[Gyan, Vivek]

Using Filter and Map

package com.java.stream;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

class Employee {
public Employee(Long id) {
this.id = id;
}

private Long id;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}
}

public class FilterwithMap {

public static void main(String[] args) {

List employees = new ArrayList<>();
// Adding Products
employees.add(new Employee(1L));
employees.add(new Employee(2L));
employees.add(new Employee(3L));
employees.add(new Employee(4L));
employees.add(new Employee(5L));
List ids = employees.stream().filter(e -> e.getId() > 1L)
.map(e -> e.getId()).collect(Collectors.toList());
System.out.println(ids);
}
}

Output
[2, 3, 4, 5]

Iterating Values

package com.java.stream;

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

class Employee{
public Employee(Long id) {
this.id = id;
}

private Long id;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}
}

public class FilterwithMap {

public static void main(String[] args) {

List employees = new ArrayList<>();
//Adding Products
employees.add(new Employee(1L));
employees.add(new Employee(2L));
employees.add(new Employee(3L));
employees.add(new Employee(4L));
employees.add(new Employee(5L));
employees.stream().filter(e -> e.getId() >1L).map(e->e.getId()).forEach(System.out::println);
}
}

output:
2
3
4
5

Finding Max and Min Values

package com.java.stream;

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

class Employee{
public Employee(Long id) {
this.id = id;
}

private Long id;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

@Override
public String toString() {
return “Employee [id=” + id + “]”;
}
}

public class FilterwithMap {

public static void main(String[] args) {

List employees = new ArrayList<>();
// Adding Products
employees.add(new Employee(1L));
employees.add(new Employee(2L));
employees.add(new Employee(3L));
employees.add(new Employee(4L));
employees.add(new Employee(5L));
Employee employeeWithMaxId = employees.stream()
.max((emp1, emp2) -> emp1.getId() > emp1.getId() ? 1 : -1)
.get();
System.out.println(“employeeWithMaxId:”+employeeWithMaxId);
Employee employeeWithMinId = employees.stream()
.min((emp1, emp2) -> emp1.getId() > emp1.getId() ? 1 : -1)
.get();
System.out.println(“employeeWithMinId:”+employeeWithMinId);
}
}

output:
employeeWithMaxId:Employee [id=5]
employeeWithMinId:Employee [id=1]

Finding the Count

package com.java.stream;

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

class Employee{
public Employee(Long id) {
this.id = id;
}

private Long id;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}
}

public class FilterwithMap {

public static void main(String[] args) {

List employees = new ArrayList<>();
//Adding Products
employees.add(new Employee(1L));
employees.add(new Employee(2L));
employees.add(new Employee(3L));
employees.add(new Employee(4L));
employees.add(new Employee(5L));
System.out.println(employees.stream().filter(e -> e.getId() > 4L).count());
}
}

output:
1

Converting List to Set and Map

package com.java.stream;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

class Employee{

private Long id;
private String name;

public Employee(Long id, String name) {
super();
this.id = id;
this.name = name;
}

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
return “Employee [id=” + id + “, name=” + name + “]”;
}
}

public class FilterwithMap {

public static void main(String[] args) {

List employees = new ArrayList<>();
//Adding Products
employees.add(new Employee(1L,”Gyan”));
employees.add(new Employee(2L,”Rochit”));
employees.add(new Employee(3L,”Vivek”));
employees.add(new Employee(4L,”Prabhakar”));
employees.add(new Employee(5L,”Praveen”));
System.out.println(employees.stream().filter(e -> e.getId() > 2L).collect(Collectors.toSet()));
System.out.println(employees.stream().filter(e -> e.getId() > 2L).collect(Collectors.toMap(e -> ((Employee) e).getId(), e -> ((Employee) e).getName())));
}
}

Output:
[Employee [id=5, name=Praveen], Employee [id=3, name=Vivek], Employee [id=4, name=Prabhakar]]
{3=Vivek, 4=Prabhakar, 5=Praveen}

Using Reduce : The reduce method can reduce the elements of a stream to a single value.

public class ReduceExample {

public static void main(String[] args) {

List array = Arrays.asList(-2, 0, 4, 6, 8);

int sum = array.stream().reduce(0,
(element1, element2) -> element1 + element2);

System.out.println(“The sum of all elements is ” + sum);

}
}

Output:
The sum of all elements is 16

Leave a Reply

Your email address will not be published. Required fields are marked *