Java 8 Stream API to find Unique Object matching a property value

Santosh picture Santosh · Nov 30, 2015 · Viewed 122.6k times · Source

Find the object matching with a Property value from a Collection using Java 8 Stream.

List<Person> objects = new ArrayList<>();

Person attributes -> Name, Phone, Email.

Iterate through list of Persons and find object matching email. Saw that this can be done through Java 8 stream easily. But that will still return a collection?

Ex:

List<Person> matchingObjects = objects.stream.
    filter(p -> p.email().equals("testemail")).
    collect(Collectors.toList());

But I know that it will always have one unique object. Can we do something instead of Collectors.toList so that i got the actual object directly.Instead of getting the list of objects.

Answer

Indrek Ots picture Indrek Ots · Nov 30, 2015

Instead of using a collector try using findFirst or findAny.

Optional<Person> matchingObject = objects.stream().
    filter(p -> p.email().equals("testemail")).
    findFirst();

This returns an Optional since the list might not contain that object.

If you're sure that the list always contains that person you can call:

Person person = matchingObject.get();

Be careful though! get throws NoSuchElementException if no value is present. Therefore it is strongly advised that you first ensure that the value is present (either with isPresent or better, use ifPresent, map, orElse or any of the other alternatives found in the Optional class).

If you're okay with a null reference if there is no such person, then:

Person person = matchingObject.orElse(null);

If possible, I would try to avoid going with the null reference route though. Other alternatives methods in the Optional class (ifPresent, map etc) can solve many use cases. Where I have found myself using orElse(null) is only when I have existing code that was designed to accept null references in some cases.


Optionals have other useful methods as well. Take a look at Optional javadoc.