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

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

    Guava API provides MoreCollectors.onlyElement() which is a collector that takes a stream containing exactly one element and returns that element.

    The returned collector throws an IllegalArgumentException if the stream consists of two or more elements, and a NoSuchElementException if the stream is empty.

    Refer the below code for usage:

    import static com.google.common.collect.MoreCollectors.onlyElement;
    
    Person matchingPerson = objects.stream
                            .filter(p -> p.email().equals("testemail"))
                            .collect(onlyElement());
    

提交回复
热议问题