Franckyi
Franckyi

Reputation: 243

Accessing to fields of all objects in list

I have a List<Foo>, where Foo is a class containing a String field named name. I want to know if the List contains a Foo object with it's name equal to "bar".

Is this possible without iterating over each object and testing them one by one ?

I'm using Java 8.

Upvotes: 4

Views: 134

Answers (1)

Jacob G.
Jacob G.

Reputation: 29710

You can use a parallel stream to return an Optional<String> which may or may not be empty, depending on if "bar" exists as an attribute for a Foo object in the List<Foo>:

list.parallelStream()
    .map(Foo::getName)
    .filter(s -> s.equals("bar"))
    .findAny();

This still iterates through the List<Foo>, but it is, at worst, O(n / # of threads used)

Another option would be to sort the list by the name attribute and then do a binary search, but it would most likely still cost a bit to sort it.

Upvotes: 2

Related Questions