A flexible filter for collections or maps
Building a proxy for http requests I came across an interesting generic problem: filter or mutate a map but only for the occurence of some given set of keys.
That's a lot of if - else - switch
The going approach is to have a specialized method with a switch:
Map<String, String> transformMap(Map<String, String> input, String joker) {
Map<String, String> result = new HashMap<>();
input.entrySet().forEach(entry -> {
String key = entry.getKey();
String value = entry.getValue();
switch (key) {
case "a":
result.put(key, "alpha");
break;
case "b":
result.put(key, "beta");
break;
case "j":
result.put(key, joker + "!");
default:
result.put(key, value);
}
});
return result;
}
This gets big and hard to maintain fast, so I was thinking of a more neutral approach entertaining Function and Optional, hear me out.
Read more
Posted by Stephan H Wissel on 04 October 2025 | Comments (0) | categories: Java