Reputation: 6361
Is there a java collection class that provides a filter method? I'm a little new to java so navigating all the collection classes and all the subtle ways they intertwine with interfaces is a little confusing. What I would like is a collection class that does the following:
FilterableCollection<SomeClass> collection = new FilterableCollection<SomeClass>();
// add some elements to the collection
// filter the collection and only keep certain elements
FilterableCollection<SomeClass> filtered_collection = collection.filter(
new Filter<SomeClass>() {
@Override
public boolean test(SomeClass obj) {
// determine whether obj passes the test or not
}
}
);
Upvotes: 1
Views: 1680
Reputation: 533442
If you are used to functional languages, using a filter is a natural choice. However in Java, using a loop is a simpler, more natural and faster choice.
// filter the collection and only keep certain elements
List<SomeClass> filtered = new ArrayList<SomeClass>();
for(SomeClass sc: collection)
if(/* determine whether sc passes the test*/)
filtered.add(sc);
You can use functional libraries but in Java these are almost always make the code more complex. Java doesn't support this programming style very well. (This may change in the future)
Upvotes: 1
Reputation: 2118
Check out this post. What is the best way to filter a Java Collection? It has a great example and should be exactly what you're looking for.
Upvotes: 3