Finding all objects that have a given property inside a collection [duplicate]
I have some complicated object, such as a Cat, which has many properties, such as age, favorite cat food, and so forth.
A bunch of Cats are stored in a Java Collection, and I need to find all the Cats that are aged 3, or those whose favorite cat food is Whiskas. Surely, I can write a custom method that finds those Cats with a specific property, but this gets cumbersome with many properties; is there some generic way of doing this?
Try the commons collections API:
List<Cat> bigList = ....; // master list
Collection<Cat> smallList = CollectionUtils.select(bigList, new Predicate() {
public boolean evaluate(Object o) {
Cat c = (Cat)o;
return c.getFavoriteFood().equals("Wiskas")
&& c.getWhateverElse().equals(Something);
}
});
Of course you don't have to use an anonymous class every time, you could create implementations of the Predicate
interface for commonly used searchs.
With Java 8 lambda expression you can do something like
cats.stream()
.filter( c -> c.getAge() == 3 && c.getFavoriteFood() == WHISKAS )
.collect(Collectors.toList());
Conceptually the same as the Guava Predicate approach, but it looks much cleaner with lambda
Probably not a valid answer for OP but worth to note for people with similar need. :)