- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Importance of the Collectors.filtering() method in Java 9?
Collectors class is an essential part of the Stream API. In Java 9, a new method: filtering() added to the Collectors class. The Collectors.filtering() method can be used for filtering elements in a stream. It is similar to the filter() method on streams. The filter() method processes the values before they have grouped whereas the filtering() method can be used nicely with the Collectors.groupingBy() method to group the values before the filtering step takes place.
Syntax
public static <T, A, R> Collector<T, ?, R> filtering(Predicate<? super T> predicate, Collector<? super T, A, R> downstream)
Example
import java.util.stream.*; import java.util.*; public class FilteringMethodTest { public static void main(String args[]) { List<String> list = List.of("x", "yy", "zz", "www"); Map<Integer, List<String>> result = list.stream() .collect(Collectors.groupingBy(String::length, Collectors.filtering(s -> !s.contains("z"), Collectors.toList()))); System.out.println(result); } }
Output
{1=[x], 2=[yy], 3=[www]}
Advertisements