Jla
Jla

Reputation: 11384

Java test specific property of an object using Collection.contains()

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

Answers (4)

Guillaume
Guillaume

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

Eyal Schneider
Eyal Schneider

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

Oliver Michels
Oliver Michels

Reputation: 2927

Consider using a Map.

Map<String,myObjects> myMap = new HashMap<String,myObjects>();
myMap.put(myObject.name,myObject);

Upvotes: 3

David M
David M

Reputation: 72930

You will have to iterate and do the comparison.

Upvotes: 3

Related Questions