Reputation: 11384
In Java how to test if a Collection of objects contains an object depending on one of its properties.
For example I would like to test if Collection<myObjects>
contains an instance of myObjects which has myObjects.name = "myName".
Upvotes: 3
Views: 1152
Reputation: 14671
You can use apache collections, they provide a bunch of handy features including predicate:
public class MyPredicate implements Predicate {
public boolean evaluate(Object input) {
return (MyObject).name = "myName";
}
}
then you can test your collection using :
CollectionUtils.find(myCollection, new MyPredicate());
This will return the first object matching the predicate or null if none matches it.
Upvotes: 2
Reputation: 22456
If you have control on how the data is collected, you can also have some kind of "reverse index" on that property; The index can be a mapping between name and a set of myObjects with that name. This way, you can efficiently retrieve all items with a given name. You can add more indexes the same way.
Upvotes: 0
Reputation: 2927
Consider using a Map.
Map<String,myObjects> myMap = new HashMap<String,myObjects>();
myMap.put(myObject.name,myObject);
Upvotes: 3