I try to throw an exception depending on which filter filtered the last element:
// Find the first person who is older than 18 and has a pet
Person firstOlderThan18AndWithPet = this.people.entrySet().stream()
.map(e -> e.getValue())
.filter(e -> e.getAge() >= 18)
.findAtLeastOne() // <-- this method doesn't exist
.orElseThrow(AgeException::new) // <-- exception because no person was older than 18
.filter(e -> e.hasPet())
.findFirst()
.orElseThrow(NoPetException::new); // <-- exception because no person older than 18 has a pet
That way I could distinguish why no person was found in the people stream. Was it because of the age or because no person has a pet.
I only see one option and do it with two streams?
List<Person> peopleOlderThan18 = this.people.entrySet().stream()
.map(e -> e.getValue())
.filter(e -> e.getAge() >= 18)
.collect(Collectors.toList());
if (0 == peopleOlderThan18.size()) {
throw new AgeException();
}
Person firstOlderThan18AndWithPet = peopleOlderThan18.stream()
.filter(e -> e.hasPet())
.findFirst()
.orElseThrow(NoPetException::new); // <-- exception because no person older than 18 has a pet
Or is there anything I could do to do everything in one stream?