We are moved to new domain
Click -> www.ehowtonow.com
Thursday, 22 June 2017

Java 8 Stream Filter and Collect Example

In this article we are going to see about Java 8 Stream filter() and collect()  example program.

StreamFilter.java
package com.javatutorialcorner.java8;

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

public class StreamFilter {

 public static void main(String[] args) {
  List batsmanRanking = new ArrayList<>();
  batsmanRanking.add("Virat Kohli");
  batsmanRanking.add("AB de Villiers");
  batsmanRanking.add("David Warner");
  batsmanRanking.add("Joe Root");
  batsmanRanking.add("Kane Williamson");
  batsmanRanking.add("Quinton de Kock");
  batsmanRanking.add("Faf du Plessis");
  batsmanRanking.add("Babar Azam");
  batsmanRanking.add("Martin Guptill");
  batsmanRanking.add("Shikhar Dhawan");

  System.out.println("Java 7 forEach : ICC One day Batsman Ranking");

  // Java 7 for each
  for (String batsman : batsmanRanking) {
   System.out.println("Name : " + batsman);

  }
  
  // Java 7 for each
  List superBatsman = new ArrayList<>();
  for (String batsman : batsmanRanking) {
   if ("AB de Villiers".equals(batsman)) {
    superBatsman.add(batsman);
   }

  }

  for (String batsman : superBatsman) {
   System.out.println("Super Batsman : " + batsman);

  }
  
  System.out.println("Java 8 Stream Filter & Collect");
   List java8SuperBatsman = batsmanRanking.stream()                // convert list to stream
                 .filter(batsman -> "AB de Villiers".equals(batsman))     // equals check AB de Villiers
                 .collect(Collectors.toList());              // collect the output and convert streams to a List

   java8SuperBatsman.forEach(System.out::println);    
   
   System.out.println("Java 8 Stream Filter & Collect");
   List topBatsmans = batsmanRanking.stream()                // convert list to stream
                 .filter(batsman -> ! "AB de Villiers".equals(batsman))     // not equals check AB de Villiers
                 .collect(Collectors.toList());              // collect the output and convert streams to a List

   topBatsmans.forEach(System.out::println);   
 }

}

Output
Java 7 forEach : ICC One day Batsman Ranking
Name : Virat Kohli
Name : AB de Villiers
Name : David Warner
Name : Joe Root
Name : Kane Williamson
Name : Quinton de Kock
Name : Faf du Plessis
Name : Babar Azam
Name : Martin Guptill
Name : Shikhar Dhawan
Super Batsman : AB de Villiers
Java 8 Stream Filter & Collect
AB de Villiers
Java 8 Stream Filter & Collect
Virat Kohli
David Warner
Joe Root
Kane Williamson
Quinton de Kock
Faf du Plessis
Babar Azam
Martin Guptill
Shikhar Dhawan



Shop and help us

Flipkart Offer Snapdeal offer Amazon.in offer Amazon.com offer
  • Blogger Comments
  • Facebook Comments
  • Disqus Comments

0 comments:

Post a Comment

Item Reviewed: Java 8 Stream Filter and Collect Example Rating: 5 Reviewed By: eHowToNow