!1102 [Fix] 修复 github issue 3380 CollectorUtil.reduceListMap与collectors.groupby一起使用时出现与预期不符的结果

Merge pull request !1102 from 阿超/v5-dev
This commit is contained in:
Looly 2023-11-12 08:43:22 +00:00 committed by Gitee
commit bb7fce8130
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
2 changed files with 24 additions and 2 deletions

View File

@ -243,8 +243,13 @@ public class CollectorUtil {
value.forEach((k, v) -> result.computeIfAbsent(k, i -> new ArrayList<>()).add(v));
return result;
}, (l, r) -> {
r.forEach((k, v) -> l.computeIfAbsent(k, i -> new ArrayList<>()).addAll(v));
return l;
R resultMap = mapSupplier.get();
resultMap.putAll(l);
r.forEach((k, v) -> {
List<V> list = resultMap.computeIfAbsent(k, i -> new ArrayList<>());
list.addAll(v);
});
return resultMap;
}
);
}

View File

@ -1,5 +1,6 @@
package cn.hutool.core.stream;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.map.MapUtil;
import org.junit.Assert;
import org.junit.Test;
@ -29,6 +30,22 @@ public class CollectorUtilTest {
Assert.assertEquals(MapUtil.builder("苏格拉底", Arrays.asList(1, 2))
.put("特拉叙马霍斯", Arrays.asList(3, 1, 2)).build(),
nameScoresMap);
List<Map<String, String>> data = ListUtil.toList(
MapUtil.builder("name", "sam").put("count", "80").map(),
MapUtil.builder("name", "sam").put("count", "81").map(),
MapUtil.builder("name", "sam").put("count", "82").map(),
MapUtil.builder("name", "jack").put("count", "80").map(),
MapUtil.builder("name", "jack").put("count", "90").map()
);
Map<String, Map<String, List<String>>> nameMap = data.stream()
.collect(Collectors.groupingBy(e -> e.get("name"), CollectorUtil.reduceListMap()));
Assert.assertEquals(MapUtil.builder("jack", MapUtil.builder("name", Arrays.asList("jack", "jack"))
.put("count", Arrays.asList("80", "90")).build())
.put("sam", MapUtil.builder("name", Arrays.asList("sam", "sam", "sam"))
.put("count", Arrays.asList("80", "81", "82")).build())
.build(), nameMap);
}
@Test