user871611 :
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:
- both surname and firstname match, return first match
- only surname matches, return first match
- none match, throw some exception
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")).???
Cyril :
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 ..."))
);
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=430639&siteId=1