I have some imperative Java conditional code that I want to refactor to use Streams.
Specifically, I have this map that I want to filter into a List based on specific filter criteria.
private Map<Integer,Thing> thingMap = new HashMap<Integer,Thing>();
// populate thingMap
And here's the code that uses it:
List<Thing> things = new ArrayList<Thing>();
for (Thing thing : thingMap.values()) {
if (thing.getCategory().equals(category)) {
if (location == null) {
things.add(thing);
} else if (thing.getLocation().equals(location)) {
things.add(thing);
}
}
}
I refactored that to the following. But what's missing is I want the location to be checked only if the category filter passes. Also, I suspect there's a better way to do this:
List<Thing> things = thingMap.entrySet()
.stream()
.filter(t -> t.getValue().getCategory().equals(category))
.filter(t ->
location == null ||
t.getValue().getLocation().equals(location)
)
.map(Map.Entry::getValue)
.collect(Collectors.toList());
What would be the idiomatic approach to retaining the layered conditional checks using Streams?