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

前端 未结 3 845
予麋鹿
予麋鹿 2021-01-30 08:07

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

List objects = new ArrayList<>();

Pe

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-30 08:48

    Instead of using a collector try using findFirst or findAny.

    Optional 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.

提交回复
热议问题