Java Streams API

Introduction

In this post, we will learn about Java Streams API and implement for Each and filter methods

What are Java 8 Streams

A Stream is a sequence of objects that support various methods which can be pipelined to produce the desired results.

A Stream is not a data structure instead it takes input from the Collections,Array or I/O channels. Streams don't change the original data structure, they only provide the result as per the pipelined methods.

Why do we need Stream?

  1. Functional Programming

  2. Code Reduce

  3. Bulk Operation

It has 2 primary methods-

  1. forEach- for iteration

  2. filter- for conditional check


For Each

For Each method is used to print each item in a list. It simplifies the concept of doing iterations to print a list of items .

Code Example:

public class ForEachDemo {

    public static void main(String[] args) {

        List<String> list=new ArrayList<>();
        list.add("Murrit");
        list.add("John");
        list.add("Peter");
        list.add("Mark");
        list.add("Carl");

        list.stream().forEach(t-> System.out.println(t));
        //o/p:-
        /*
        Murrit
        John
        Peter
        Mark
        Carl
         */

        Map<Integer,String> map=new HashMap<>();
        map.put(1,"a");
        map.put(2,"b");
        map.put(3,"c");
        map.put(4,"d");

        map.entrySet().stream().forEach(obj-> System.out.println(obj));
        /*
        o/p:-
        1=a
        2=b
        3=c
        4=d
         */

        //for each internally uses consumer functional interface
        Consumer<String> consumer=(t)-> System.out.println(t);
        for(String s1:list){
            consumer.accept(s1);
        }

        /*
        o/p:
        Murrit
        John
        Peter
        Mark
        Carl
         */
    }
}

Filter

Filter method is used to print certain items only based on condition. It simplifies the concept of conditional checks in a list of objects.

Code Example:

public static void main(String[] args) {

        List<String> list=new ArrayList<>();
        list.add("Murrit");
        list.add("John");
        list.add("Peter");
        list.add("Mark");
        list.add("Carl");

        list.stream().filter((t)->t.startsWith("M")).forEach(t-> System.out.println(t));

        /*
        o/p:-
        Murrit
        Mark
         */

        Map<Integer,String> map=new HashMap<>();
        map.put(1,"a");
        map.put(2,"b");
        map.put(3,"c");
        map.put(4,"d");

        map.entrySet().stream().filter(k->k.getKey()%2==0).forEach(obj-> System.out.println(obj));

        /*
        o/p:-
        2=b
        4=d
         */
    }

Real-world Example for Java Stream

Suppose there is a list of employees and we want to dynamically print the list of employees who falls under Income tax limit(> 700000) then we can use Java Streams to acheive this

Code Example:-

Employee.java

public class Employee {

    private int id;
    private String name;
    private String dept;
    private long salary;

    //Constructors,getter and setters, to string
}

DAO.java

 public static List<Employee> getEmployees(){
        List<Employee> list=new ArrayList<>();
        list.add(new Employee(176,"Roshan","IT",600000));
        list.add(new Employee(177,"Vinay","CSE",900000));
        list.add(new Employee(178,"Vikas","IT",800000));
        list.add(new Employee(179,"Ramit","CSE",500000));

        return list;
    }

TaxService.java

public class TaxService {

    public static List<Employee> evaluateTaxUsers(String input){
        if(input.equalsIgnoreCase("tax")){
            return DAO.getEmployees().stream().filter(emp->emp.getSalary()>700000).collect(Collectors.toList());
        }else{
            return DAO.getEmployees().stream().filter(emp->emp.getSalary()<700000).collect(Collectors.toList());
        }

    }

    public static void main(String[] args) {
        System.out.println(evaluateTaxUsers("tax"));
        //o/p:-
        //[Employee{id=177, name='Vinay', dept='CSE', salary=900000}, Employee{id=178, name='Vikas', dept='IT', salary=800000}]
    }
}

Summary

In this post, we have learned about Java streams API.

Thank you for reading. If you found this article helpful, react and share. Cheers.