Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 870
Santosh Avatar asked Nov 30 '15 06:11

Santosh


People also ask

How do I get unique values from a collection stream?

distinct() returns a stream consisting of distinct elements in a stream. distinct() is the method of Stream interface. This method uses hashCode() and equals() methods to get distinct elements. In case of ordered streams, the selection of distinct elements is stable.

How do you filter a list of objects using a stream?

Java stream provides a method filter() to filter stream elements on the basis of given predicate. Suppose you want to get only even elements of your list then you can do this easily with the help of filter method. This method takes predicate as an argument and returns a stream of consisting of resulted elements.


1 Answers

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.

like image 134
Indrek Ots Avatar answered Sep 20 '22 11:09

Indrek Ots