27 October, 2018

Java 8 Stream Filter with Example


In this article we will learn how to use Java 8 Stream Filter with Example,  I have used String list to filter the names. Stream, A sequence of elements supporting sequential and parallel aggregate operations. Below example will show you how to filter the list with predicate.


StringFilterUsingStream.java 



package com.javadevelopersguide.tutorial;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
 * @author manoj.bardhan
 *
 */
public class StringFilterUsingStream {
public static void main(String[] str) {
List<String> nameList = new ArrayList<String>();
nameList.add("Roshna");
nameList.add("Amit Kumar");
nameList.add("Manoj");
nameList.add("Neha");
nameList.add("Rina");
nameList.add("Ashna");
nameList.add("Peter");
nameList.add("Deb Kumar");
System.out.println("All Names ::");
nameList.stream().forEach(name -> System.out.println(name));
// Filter all names ends with "Kumar"
List<String> filteredList = nameList.stream().filter(nam -> nam.endsWith("Kumar")).collect(Collectors.toList());
System.out.println("\nFiltered Names ::");
filteredList.stream().forEach(name -> System.out.println(name));
}
}





Output :


All Names ::

Roshna
Amit Kumar
Manoj
Neha
Rina
Ashna
Peter
Deb Kumar

Filtered Names ::

Amit Kumar
Deb Kumar


Hope this will help you. Happy Learning.





3 comments:

  1. Thanks for Sharing this Informative Information this is very Helpful for Beginners, I like this

    Devops Online Training

    ReplyDelete
  2. Its really nice and interesting article you have shared with us which is informative and knowledgeable. Thanks for sharing this great.Professional Web design services are provided by W3BMINDS- Website designer in Lucknow.
    Web development Company | Web design company

    ReplyDelete
  3. Good Post. I like your blog. Thanks for Sharing
    Java Training in Noida

    ReplyDelete