Reputation: 243
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
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