开发者

Eclipse Display view and checking if list contains object with some property

开发者 https://www.devze.com 2023-03-25 02:01 出处:网络
i have Class ComplexObject { Complex() {} public String first; public开发者_Go百科 String second; }

i have

 Class ComplexObject {
      Complex() {}
      public String first;
      public开发者_Go百科 String second;
 }

 List<ComplexObject> allObjects = fillListWithSomeData();

Is there some way in Display view to check if allObjects list contains object with field first set to "foobar" ?


I guess you need this:

for (ComplexObject obj : allObjects)
   if (obj.first.equals("foobar")) {
       //we have found one
   }


Unless you have a equals() and hashCode() method implemented in the ComplexObject class using the first field, you cannot.

Your only option otherwise is to iterate through the list and do a compare on the field value.


Here is a very generic solution for any type and any type of comparison:

public static <T> boolean containsSimilar(T toCompare, List<T> toSearch, Comparator<T> comp) {
   for (T item: toSearch) {
      if (comp.compare(toCompare, item) == 0)
          return true;
   }
   return false;
}

You would use it like so:

boolean contains = containsSimilar(lookingFOr, listOfObjects, 
   new Comparator<ComplexObject>() { 
      public int compare(ComplexObject one, ComplexObject two) {
         // your compare logic here
      }
      public boolean equals(Object o) { }
});

Where lookingFor is a ComplexObject with the properties set to what you want to find, and listOfObjects is a list of ComplexObject.

0

精彩评论

暂无评论...
验证码 换一张
取 消