I want to filter a java.util.Collection
based on a predicate.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
My answer builds on that from Kevin Wong, here as a one-liner using
CollectionUtils
from spring and a Java 8 lambda expression.This is as concise and readable as any alternative I have seen (without using aspect-based libraries)
Spring CollectionUtils is available from spring version 4.0.2.RELEASE, and remember you need JDK 1.8 and language level 8+.
Use CollectionUtils.filter(Collection,Predicate), from Apache Commons.
Let’s look at how to filter a built-in JDK List and a MutableList using Eclipse Collections (formerly GS Collections).
If you wanted to filter the numbers less than 3, you would expect the following outputs.
Here’s how you can filter using an anonymous inner class as the
Predicate
.Here are some alternatives to filtering JDK lists and Eclipse Collections MutableLists using the Predicates factory.
Here is a version that doesn't allocate an object for the predicate, by using the Predicates2 factory instead with the
selectWith
method that takes aPredicate2
.Sometimes you want to filter on a negative condition. There is a special method in Eclipse Collections for that called
reject
.Here’s how you can filter using a Java 8 lambda as the
Predicate
.The method
partition
will return two collections, containing the elements selected by and rejected by thePredicate
.Note: I am a committer for Eclipse Collections.