Looking to come up with a way to apply a filter on the original stream if a previous filter returned an empty stream. For instance:
- Given a stream of numbers
- Get and return all even numbers
- If none, get and return all numbers that are a multiple of 3
- If none, get and return all numbers that are a multiple of 5
- etc..
A trivial approach to this would be:
List<Integer> numbers = ...
List<Integer> filteredNums = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
if (filteredNums.isEmpty()) {
filteredNums = numbers.stream()
.filter(n -> n % 3 == 0)
.collect(Collectors.toList());
}
if (filteredNums.isEmpty()) {
filteredNums = numbers.stream()
.filter(n -> n % 5 == 0)
.collect(Collectors.toList());
}
Given a list of numbers such as 1, 3, 5, 15, 21, would result in 3,15,21.
My example with numbers is a simplified version of what I'm trying to do, but conveys the same concept. I could create a Collector to do this, but in general I feel there is something simple I'm missing. Ideally I'd like the solution to be able to be used in a stream so I can continue performing additional stream operations on it. In this scenario, maybe I'd want to reduce it to a sum or map where I multiple each number and the collect into a list.