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

前端 未结 3 903
予麋鹿
予麋鹿 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:46

    findAny & orElse

    By using findAny() and orElse():

    Person matchingObject = objects.stream().
    filter(p -> p.email().equals("testemail")).
    findAny().orElse(null);
    

    Stops looking after finding an occurrence.

    findAny

    Optional findAny()

    Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty. This is a short-circuiting terminal operation. The behavior of this operation is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations; the cost is that multiple invocations on the same source may not return the same result. (If a stable result is desired, use findFirst() instead.)

提交回复
热议问题