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.
This question is related to
java
filter
java-8
java-stream
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());
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<T> 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.)
Source: Stackoverflow.com