[英]Can we use java Stream to refactor this?
是否可以在Java 8中使用Stream
s 重構以下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;}));
試試這個:
Map<StateEnum, List<List<ThreadDo>>> stateDumpListMap = dumpDoList.stream()
.flatMap(dumpDo -> getStateGroup(dumpDo).entrySet().stream())
.collect(Collectors.groupingBy(
entry -> entry.getKey(),
Collectors.mapping(entry -> entry.getValue(), Collectors.toList())));
還有一個選項,以collect
:
Map<StateEnum, List<List<ThreadDo>>> stateDumpListMap = dumpDoList.stream()
.map(this::getStateGroup) // dumpDo mapped to stateDoListMap ( Map<StateEnum, List<ThreadDo>> )
.map(Map::entrySet) // stream of sets of entries of stateDoListMap (Entry<StateEnum, List<ThreadDo>>)
.flatMap(Set::stream) // stream of entries of all stateDoListMaps
.collect(HashMap::new, // collect to a new HashMap, types infered from the variable declaration
(map, stateDoListMapEntry) -> map.computeIfAbsent(stateDoListMapEntry.getKey(), key -> new ArrayList<>()).add(stateDoListMapEntry.getValue()), // for each entry incoming from the stream, compute it if does not exist in the target map yet (create the top level list), then add List<ThreadDo> to it.
Map::putAll);
三參數collect
允許指定它返回的映射的精確實現。 可能有也可能沒有必要控制它 - 取決於你需要的地圖。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.