My aim is to filter for a best match. In my example I have a list of persons, which I want to filter by surname and firstname.
The matching prescendence would be:
My code so far:
final List<Person> persons = Arrays.asList(
new Person("Doe", "John"),
new Person("Doe", "Jane"),
new Person("Munster", "Herman");
Person person = persons.stream().filter(p -> p.getSurname().equals("Doe")).???
2.1. Multiple Filters. The Stream API allows chaining multiple filters. We can leverage this to satisfy the complex filtering criteria described.
Stream filter(Predicate predicate) returns a stream consisting of the elements of this stream that match the given predicate. This is an intermediate operation.
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.
The performance of both streams degrades fast when the number of values increases. However, the parallel stream performs worse than the sequential stream in all cases.
Assuming Person implements equals and hashCode:
Person personToFind = new Person("Doe", "Jane");
Person person = persons.stream()
.filter(p -> p.equals(personToFind))
.findFirst()
.orElseGet(() ->
persons.stream()
.filter(p -> p.getSurname().equals(personToFind.getSurname()))
.findFirst()
.orElseThrow(() -> new RuntimeException("Could not find person ..."))
);
You can use
Person person = persons.stream()
.filter(p -> p.getSurName().equals("Doe"))
.max(Comparator.comparing(p -> p.getFirstName().equals("Jane")))
.orElse(null);
It will only consider elements having the right surname and return the best element of them, which is the one with a matching first name. Otherwise, the first matching element is returned.
As already mentioned in a comment, a for
loop could be more efficient if there is a best element, as it can short circuit. If there is no best element with matching surname and first name, all element have to be checked in all implementations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With