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
I know this is an old question, but...
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).
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
}