Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 471
Jake Avatar asked Feb 25 '09 19:02

Jake


People also ask

What type of collection can hold duplicate object?

LinkedList implements the Collection interface. It uses a doubly linked list internally to store the elements. It can store the duplicate elements.

Does a collection object store copies of other objects?

Does a collection object store copies of other objects? A: No, a collection object works with reference types. It stores references of other objects, not copies of other objects.

How can we access elements of a collection?

Java provides Iterator and ListIterator classes to retrieve the elements of the collection object. The hasNext() method of these interfaces returns true if the collection object has next element else it returns false. The next() methods of the Iterator and ListIterator returns the next element of the collection.

Which collection type is faster if you have to find an item?

If you need fast add and removal of elements, use LinkedList (but it has a very poor seeking performance).


2 Answers

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.

like image 138
Brian Dilley Avatar answered Sep 21 '22 04:09

Brian Dilley


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. :)

like image 33
Adrian Shum Avatar answered Sep 20 '22 04:09

Adrian Shum