I need to refactor my below stream code:
List<Map<String, Integer>> list5 = new ArrayList<>();
map3 = new HashMap<>();
map3.put("foo", 1);
map3.put("bar", 2);
map3.put("zzz", 6);
list5.add(map3);
map3 = new HashMap<>();
map3.put("foo", 3);
map3.put("bar", 4);
map3.put("zzz", null);
list5.add(map3);
//new list with processed maps
List<Map<String, Integer>> list6 = list5.stream()
.map(hashmap -> {
Map<String, Integer> newMap = hashmap.entrySet().stream()
.collect(HashMap::new, (m, v) -> {
if (v.getKey().equals("bar")) {
m.put(v.getKey(), v.getValue() * 2);
} else {
m.put(v.getKey(), v.getValue());
}
}, HashMap::putAll);
return newMap;
})
.collect(toList());
System.out.println(list6);
I need a way to extract/refactor the below logic only from the above stream code, since this piece will only change in other list of maps that I have:
if (v.getKey().equals("bar")) {
m.put(v.getKey(), v.getValue() * 2);
} else {
m.put(v.getKey(), v.getValue());
}
Using IntelliJ it adds a biconsumer to main() itself, which is not expected here and removes the code. I need a way to extract it separately something like below:
List<Map<String, Integer>> list6 = list5.stream()
.map(hashmap -> {
Map<String, Integer> newMap = hashmap.entrySet().stream()
.collect(HashMap::new, (m, v) -> {
biconsumerLogic1.accept(m, v);
}, HashMap::putAll);
return newMap;
})
.collect(toList());
And biconsumerLogic1 is a separate functional interface like:
BiConsumer biconsumerLogic1() {
accept(m, v) {
//logic goes here...
}
}
How do I achieve that? Any pointers are appreciated.
Thanks..