Java 8 Stream API Examples

Hello Friends,

In this post, we will discuss Java 8 Stream API Examples.

So what we are going to do is, we will create a Player class, create multiple objects of Player class and then create a test class where will retrieve data of players using Stream API.First example is with normal Stream(which we can call Serial Stream) and second example is with parallel stream.




Serial Stream

As a first step, Let us create a Player class.

public class Player {

    private String name;
    private int id;
    private int fees;
    private String grade;

    public Player(String name, int id, int fees, String grade) {
        super();
        this.name = name;
        this.id = id;
        this.fees = fees;
        this.grade = grade;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the id
     */
    public int getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(int id) {
        this.id = id;
    }

    /**
     * @return the fees
     */
    public int getFees() {
        return fees;
    }

    /**
     * @param fees the fees to set
     */
    public void setFees(int fees) {
        this.fees = fees;
    }

    /**
     * @return the grade
     */
    public String getGrade() {
        return grade;
    }

    /**
     * @param grade the grade to set
     */
    public void setGrade(String grade) {
        this.grade = grade;
    }

    @Override
    public String toString() {
        return "Player [name=" + name + ", id=" + id + ", fees=" + fees + ", grade=" + grade + "]";
    }
}

Now, let us create a test class to test Stream API.

public class TestJava8Streams {

    public static void main(String[] args) {
        List<Player> players = createPlayerList();
       /**********STREAM****************/
        System.out.println("STREAM");
       /****Get List of Players Who are in Grade AA***/
        System.out.println("Grade AA Players :");
        players.stream().filter((Player player1)-> player1.getGrade().equalsIgnoreCase("AA")).collect(Collectors.toList()).forEach(System.out::println);
        /*********************************************/

        /********Get Fee of Grade AA Players**********/
        System.out.println("Fee Grade AA Players :");
        players.stream().filter((Player player1)-> player1.getGrade().equalsIgnoreCase("AA")).map(p->p.getFees()).collect(Collectors.toList()).forEach(System.out::println);;
        /*********************************************/
        /********Are All players getting Match Fee of more than 3 Crore*****/
        System.out.println("Does All Players getting Match Fee of more than 3 Crores:");
        boolean isAllPlayerHavingFeeMoreThansThreeCrore1 = players.stream().allMatch(player1 -> player1.getFees()>=30000000);
        System.out.println(isAllPlayerHavingFeeMoreThansThreeCrore1 ? "Yes": "No");
        /*******************************************************************/
        /********Are All players getting Match Fee of more than 1 Crore*****/
        System.out.println("Does All Players getting Match Fee equal to or more than 1 Crore:");
        boolean isAllPlayerHavingFeeMoreThansOneCrore1 = players.stream().allMatch(player1 -> player1.getFees()>=10000000);
        System.out.println(isAllPlayerHavingFeeMoreThansOneCrore1 ? "Yes": "No");
        /*******************************************************************/
        /*************Get Players with their Name and Grade******************/
        players.stream().collect(Collectors.toMap((Player player1)-> player1.getName(), (Player player1)-> player1.getGrade()));
        players.forEach(player1 -> System.out.println("Player Name:"+player1.getName() + " | " + "Player Grade:"+player1.getGrade()));
        /*******************************************************************/
        /*************Get any player detail.As per java docs ,multiple invocations can return different results******/
        Optional<Player> player1 =players.stream().findAny();
        System.out.println("Any Player:"+player1.get());
        /*******************************************************************/
        /********Get First Player in the list*****/
        String firstPlayerName = players.stream().findFirst().get().getName();
        System.out.println("First Player in the list:"+ firstPlayerName);
        /****************************************/
        /********Get First Two Players from the list******/
        System.out.println("First two Players in the list:");
        players.stream().limit(2).collect(Collectors.toList()).forEach(System.out::println);;
        /************************************************/
        /********Player whose name alphabetically comes Last in the list******/
        Optional<Player> alphabeticallyLast1 = players.stream().max((Player st1,Player st2)-> st1.getName().compareToIgnoreCase(st2.getName()));
        System.out.println("Alphabetically last Player:"+alphabeticallyLast1.get().getName());
        /************************************************/
        /********Player whose name alphabetically comes First in the list******/
        Optional<Player> alphabeticallyFirst1 = players.stream().min((Player st1,Player st2)-> st1.getName().compareToIgnoreCase(st2.getName()));
        System.out.println("Alphabetically first Player::"+alphabeticallyFirst1.get().getName());
        /**********************************************************************/
    }
    private static List<Player> createPlayerList(){
        List<Player> palyers = new ArrayList<Player>();
        Player player2 = new Player("Dhawan",101,70000000,"AA");
        Player player1 = new Player("Rohit",102,70000000,"AA");
        Player player3 = new Player("Rahane",201,50000000,"A");
        Player player4 = new Player("Dhoni",202,50000000,"A");
        Player player5 = new Player("Raina",301,10000000,"C");
        Player player6 = new Player("Kohli",302,70000000,"AA");
        Player player7 = new Player("Jadeja",401,50000000,"A");
        Player player8 = new Player("Bumrah",402,70000000,"AA");
        Player player9 = new Player("Umesh",403,30000000,"B");
        Player player10 = new Player("Karthik",404,30000000,"B");
        Player player11 = new Player("Pandey",405,10000000,"C");
        palyers.add(player1);
        palyers.add(player2);
        palyers.add(player3);
        palyers.add(player4);
        palyers.add(player5);
        palyers.add(player6);
        palyers.add(player7);
        palyers.add(player8);
        palyers.add(player9);
        palyers.add(player10);
        palyers.add(player11);
        return palyers;
    }
}


Here is the ouput:

Grade AA Players :

Player [name=Rohit, id=102, fees=70000000, grade=AA, addresses=null]

Player [name=Dhawan, id=101, fees=70000000, grade=AA, addresses=null]

Player [name=Kohli, id=302, fees=70000000, grade=AA, addresses=null]

Player [name=Bumrah, id=402, fees=70000000, grade=AA, addresses=null]

Fee Grade AA Players :

70000000

70000000

70000000

70000000

Does All Players getting Match Fee of more than 3 Crores:false

Does All Players getting Match Fee equal to or more than 1 Crore:true

Player Name:Rohit | Player Grade:AA

Player Name:Dhawan | Player Grade:AA

Player Name:Rahane | Player Grade:A

Player Name:Dhoni | Player Grade:A

Player Name:Raina | Player Grade:C

Player Name:Kohli | Player Grade:AA

Player Name:Jadeja | Player Grade:A

Player Name:Bumrah | Player Grade:AA

Player Name:Umesh | Player Grade:B

Player Name:Karthik | Player Grade:B

Player Name:Pandey | Player Grade:C

Any Player:Player [name=Rohit, id=102, fees=70000000, grade=AA, addresses=null]

First Player in the list:Player [name=Rohit, id=102, fees=70000000, grade=AA, addresses=null]

First two Players in the list:

Player [name=Rohit, id=102, fees=70000000, grade=AA, addresses=null]

Player [name=Dhawan, id=101, fees=70000000, grade=AA, addresses=null]

Sorted List of PLayers according to their name in Alphabetical order:

Player [name=Bumrah, id=402, fees=70000000, grade=AA, addresses=null]

Player [name=Dhawan, id=101, fees=70000000, grade=AA, addresses=null]

Player [name=Dhoni, id=202, fees=50000000, grade=A, addresses=null]

Player [name=Jadeja, id=401, fees=50000000, grade=A, addresses=null]

Player [name=Karthik, id=404, fees=30000000, grade=B, addresses=null]

Player [name=Kohli, id=302, fees=70000000, grade=AA, addresses=null]

Player [name=Pandey, id=405, fees=10000000, grade=C, addresses=null]

Player [name=Rahane, id=201, fees=50000000, grade=A, addresses=null]

Player [name=Raina, id=301, fees=10000000, grade=C, addresses=null]

Player [name=Rohit, id=102, fees=70000000, grade=AA, addresses=null]

Player [name=Umesh, id=403, fees=30000000, grade=B, addresses=null]

Alphabetically last Player:Umesh

Alphabetically first Player::Bumrah

Parallel Stream

Below is the same example using Parallel Streams

Below code is exactly same except that instead of stream() method, we will call parallelStream() method.
public class TestJava8ParallelStream {

    public static void main(String[] args) {

        List<Player> players = createPlayerList();
        /****PARALLEL STREAM****************/
        System.out.println("PARALLEL STREAM");
        /****Get List of Players Who are in Grade AA***/
        System.out.println("Grade AA Players :");
        players.parallelStream().filter((Player player1) -> player1.getGrade().equalsIgnoreCase("AA")).collect(Collectors.toList()).forEach(System.out::println);
        /*********************************************/

        /********Get Fee of Grade AA Players**********/
        System.out.println("Fee Grade AA Players :");
        players.parallelStream().filter((Player player1) -> player1.getGrade().equalsIgnoreCase("AA")).map(p -> p.getFees()).collect(Collectors.toList()).forEach(System.out::println);;
        /*********************************************/
        /********Are All players getting Match Fee of more than 3 Crore*****/
        System.out.println("Does All Players getting Match Fee of more than 3 Crores:");
        boolean isAllPlayerHavingFeeMoreThansThreeCrore1 = players.parallelStream().allMatch(player1 -> player1.getFees() >= 30000000);
        System.out.println(isAllPlayerHavingFeeMoreThansThreeCrore1 ? "Yes" : "No");
        /*******************************************************************/
        /********Are All players getting Match Fee of more than 1 Crore*****/
        System.out.println("Does All Players getting Match Fee equal to or more than 1 Crore:");
        boolean isAllPlayerHavingFeeMoreThansOneCrore1 = players.parallelStream().allMatch(player1 -> player1.getFees() >= 10000000);
        System.out.println(isAllPlayerHavingFeeMoreThansOneCrore1 ? "Yes" : "No");
        /*******************************************************************/
        /*************Get Players with their Name and Grade******************/
        players.parallelStream().collect(Collectors.toMap((Player player1) -> player1.getName(), (Player player1) -> player1.getGrade()));
        players.forEach(player1 -> System.out.println("Player Name:" + player1.getName() + " | " + "Player Grade:" + player1.getGrade()));
        /*******************************************************************/
        /*************Get any player detail.As per java docs ,multiple invocations can return different results******/
        Optional<Player> player1 = players.parallelStream().findAny();
        System.out.println("Any Player:" + player1.get());
        /*******************************************************************/
        /********Get First Player in the list*****/
        String firstPlayerName = players.parallelStream().findFirst().get().getName();
        System.out.println("First Player in the list:" + firstPlayerName);
        /****************************************/
        /********Get First Two Players from the list******/
        System.out.println("First two Players in the list:");
        players.parallelStream().limit(2).collect(Collectors.toList()).forEach(System.out::println);
        ;
        /************************************************/
        /********Player whose name alphabetically comes Last in the list******/
        Optional<Player> alphabeticallyLast1 = players.parallelStream().max((Player st1, Player st2) -> st1.getName().compareToIgnoreCase(st2.getName()));
        System.out.println("Alphabetically last Player:" + alphabeticallyLast1.get().getName());
        /************************************************/
        /********Player whose name alphabetically comes First in the list******/
        Optional<Player> alphabeticallyFirst1 = players.parallelStream().min((Player st1, Player st2) -> st1.getName().compareToIgnoreCase(st2.getName()));
        System.out.println("Alphabetically first Player::" + alphabeticallyFirst1.get().getName());
        /**********************************************************************/
    }

    private static List<Player> createPlayerList() {
        List<Player> palyers = new ArrayList<Player>();
        Player player2 = new Player("Dhawan", 101, 70000000, "AA");
        Player player1 = new Player("Rohit", 102, 70000000, "AA");
        Player player3 = new Player("Rahane", 201, 50000000, "A");
        Player player4 = new Player("Dhoni", 202, 50000000, "A");
        Player player5 = new Player("Raina", 301, 10000000, "C");
        Player player6 = new Player("Kohli", 302, 70000000, "AA");
        Player player7 = new Player("Jadeja", 401, 50000000, "A");
        Player player8 = new Player("Bumrah", 402, 70000000, "AA");
        Player player9 = new Player("Umesh", 403, 30000000, "B");
        Player player10 = new Player("Karthik", 404, 30000000, "B");
        Player player11 = new Player("Pandey", 405, 10000000, "C");
        palyers.add(player1);
        palyers.add(player2);
        palyers.add(player3);
        palyers.add(player4);
        palyers.add(player5);
        palyers.add(player6);
        palyers.add(player7);
        palyers.add(player8);
        palyers.add(player9);
        palyers.add(player10);
        palyers.add(player11);
        return palyers;
    }
}

Here is the Output With Parallel Stream

Grade AA Players :

Player [name=Rohit, id=102, fees=70000000, grade=AA, addresses=null]

Player [name=Dhawan, id=101, fees=70000000, grade=AA, addresses=null]

Player [name=Kohli, id=302, fees=70000000, grade=AA, addresses=null]

Player [name=Bumrah, id=402, fees=70000000, grade=AA, addresses=null]

Fee Grade AA Players :

70000000

70000000

70000000

70000000

Does All Players getting Match Fee of more than 3 Crores:false

Does All Players getting Match Fee equal to or more than 1 Crore:true

Player Name:Rohit | Player Grade:AA

Player Name:Dhawan | Player Grade:AA

Player Name:Rahane | Player Grade:A

Player Name:Dhoni | Player Grade:A

Player Name:Raina | Player Grade:C

Player Name:Kohli | Player Grade:AA

Player Name:Jadeja | Player Grade:A

Player Name:Bumrah | Player Grade:AA

Player Name:Umesh | Player Grade:B

Player Name:Karthik | Player Grade:B

Player Name:Pandey | Player Grade:C

Any Player:Player [name=Rohit, id=102, fees=70000000, grade=AA, addresses=null]

First Player in the list:Player [name=Rohit, id=102, fees=70000000, grade=AA, addresses=null]

First two Players in the list:

Player [name=Rohit, id=102, fees=70000000, grade=AA, addresses=null]

Player [name=Dhawan, id=101, fees=70000000, grade=AA, addresses=null]

Alphabetically last Player:Umesh

Alphabetically first Player::Bumrah

That's all on Java 8 Stream API examples. 


Feel free to post any questions in comments section or to share this post with anyone.

Also,if you like JavaSolutionsGuide and want to contribute,go ahead and

- Write an article
- Share with me at javasolutionsguide@gmail.com and

- See Your Article Getting Published on main Page of JavaSolutionsGuide with your name.

Also for Java 8 features ULTIMATE GUIDE, check Java 8 Features -Ultimate Guide