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.
Follow for more details on @Facebook!!!
Find More :-
Find More :-
- Write your first groovy program.
- Top 10 groovy interview question.
- Difference between groovy and java.
- What is full stack development experience.
- 5 fundamental questions of groovy.
- Write your first java program.
- Reverse string using recursive method in java.
- Java 8 use Option - avoid NullPointerException
- Producer & Consumer problem solution using BlockingQueue.
- Comparator Interface with Examples