How to check in java if Set contains object with some string value?

后端 未结 6 1521
北荒
北荒 2020-12-16 10:19

I have Set of objects. Each object has String value.

I need to select all objects that have this value equal to \"direction\".

Is it possibl

6条回答
  •  萌比男神i
    2020-12-16 11:11

    I know this is an old question, but...

    Short answer: NO, it's not possible...

    Using equals() or contains() as recommended by other fellows should be restricted to situations where the attributes you are using for filtering are actually a part of the objects Identity. I don't see any way but a O(n) algorithm.

    If you are considering native functions, Java 8 brought the Stream API and concepts of Functional Programming, allowing easier and cleaner loop calls. Nonetheless it is worth noting that for your situation all objects in your collection will have to be checked, so complexity will remain O(n).

    Example with Java 8's stream().filter()

    public static void main(String[] args...){
        Set mySet = new HashSet<>();
        mySet.add(new MyClass("Obj 1", "Rio de Janeiro"));
        mySet.add(new MyClass("Obj 2", "London"));
        mySet.add(new MyClass("Obj 3", "New York"));
        mySet.add(new MyClass("Obj 4", "Rio de Janeiro"));
    
        Set filtered = mySet.stream()
                                     .filter(mc -> mc.getCity().equals('Rio de Janeiro'))
                                     .collect(Collectors.toSet());
    
        filtered.forEach(mc -> System.out.println("Object: "+mc.getName()));
    
        // Result:
        //    Object: Obj 1 
        //    Object: Obj 4 
    }
    

提交回复
热议问题