是否可以在 Java 8 中使用 Stream
来重构以下 for
循环?
在收集不同来源的列表时将状态从内部移动到外部?
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());
});
}
最近我尝试了几个用例,但对我来说似乎很难看。
我尝试使用 stream().map()
来实现这一点,但我失败了。有人可以帮忙吗?
最佳答案
这里有一种方法,使用collect
代替forEach
生成Map
,使用flatMap
消除for
循环:
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;}));
正如 Aominè 所说,可以简化为:
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;}));
关于java - 我们可以使用 java Stream 来重构它吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50714245/