Is it possible to refactor the following for
loop using Stream
s in Java 8?
Moving the state from the inside to outside while collecting the list for different sources?
Map<StateEnum, List<List<ThreadDo>>> stateDumpListMap = new HashMap<>();
for (ThreadDumpDo dumpDo : dumpDoList) {
Map<StateEnum, List<ThreadDo>> stateDoListMap = getStateGroup(dumpDo);
stateDoListMap.entrySet().stream().forEach(entry -> {
stateDumpListMap.putIfAbsent(entry.getKey(), new ArrayList<>());
stateDumpListMap.get(entry.getKey()).add(entry.getValue());
});
}
Recently I tried several use cases but it just seems ugly to me.
I tried to use stream().map()
to achieve that, but I failed. Can anyone please help?
Here's one way, using collect
instead of forEach
to generate the Map
, and using flatMap
to eliminate the for
loop:
Map<StateEnum, List<List<ThreadDo>>> stateDumpListMap =
dumpDoList.stream ()
.flatMap (d->getStateGroup(d).entrySet().stream ())
.collect(Collectors.toMap (Map.Entry::getKey,
e -> {
List<List<ThreadDo>> l = new ArrayList<>();
l.add (e.getValue());
return l;
},
(v1,v2)->{v1.addAll(v2);return v1;}));
Which, as Aominè commented, can be simplified to:
Map<StateEnum, List<List<ThreadDo>>> stateDumpListMap =
dumpDoList.stream ()
.flatMap (d->getStateGroup(d).entrySet().stream ())
.collect(Collectors.toMap (Map.Entry::getKey,
e -> new ArrayList<>(Collections.singletonList(e.getValue())),
(v1,v2)->{v1.addAll(v2);return v1;}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With