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

In Java, how to check if a collection of objects contains an object that depends on one of its properties.

For example, I would like to check if it Collection<myObjects>contains an instance of myObjects that has myObjects.name = "myName".

+3
source share
4 answers

You will have to iterate and perform the comparison.

+3
source

Consider using a map.

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

apache, , :

public class MyPredicate implements Predicate {
  public boolean evaluate(Object input) {
    return (MyObject).name = "myName";
  }
}

, :

   CollectionUtils.find(myCollection, new MyPredicate());

, , null, .

+2

If you have control over how data is collected, you can also have some kind of “reverse index” for this property; An index can be a mapping between a name and a set of myObject objects with that name. Thus, you can effectively get all the elements with the given name. You can add other indexes in the same way.

0
source

Source: https://habr.com/ru/post/1742430/


All Articles