我正在尝试使用streams收集器来获得映射groupId -> List of elements
。我的情况的特别之处在于,一个元素可以属于多个组。
为了用一个简单的例子来演示它:假设我想使用数字2 - 10
作为分组的标识符,并且希望对数字2 - 40
进行分组,这样它们就可以被看作是标识符的倍数。传统上,我会这样做:
Map<Integer,List<Integer>> map = new HashMap<>();
for(int i = 2; i < 11; i++){
for(int j = 2; j < 41; j++){
if(j%i == 0)
map.computeIfAbsent(i, k -> new ArrayList<>()).add(j);
}
}
map.forEach((k,v) -> {
System.out.println(k + " : " + v);
});
得到这样的东西
2 : [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40]
3 : [3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39]
4 : [4, 8, 12, 16, 20, 24, 28, 32, 36, 40]
5 : [5, 10, 15, 20, 25, 30, 35, 40]
6 : [6, 12, 18, 24, 30, 36]
7 : [7, 14, 21, 28, 35]
8 : [8, 16, 24, 32, 40]
9 : [9, 18, 27, 36]
10 : [10, 20, 30, 40]
为了使用streams,我尝试将this问题的答案应用到我的案例中,但没有成功。
IntStream.range(2, 11).boxed()
.flatMap(g -> IntStream.range(2, 41)
.boxed()
.filter(i -> i%g == 0)
.map(i -> new AbstractMap.SimpleEntry<>(g,i))
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, Collectors.toList()))));
我得到一个编译错误
不兼容类型:推理变量R#1具有不兼容边界等式约束: Map下界: Stream<?扩展R#2>对象,其中R#1,A#1,T#1,K,T#2,A#2,D,R#2是类型变量: R#1扩展对象在方法collect(Collector<??超级T#1,A#1,R#1>) A#1扩展对象在方法collect(Collector<??超级T#1,A#1,R#1>) T#1扩展接口中声明的对象流K扩展对象在方法groupingBy(Function<??超级T#2?扩展K>,Collector<?超级T#2,A#2,D>) T#2扩展对象在方法groupingBy中声明(Function<?超级T#2?扩展K>,Collector<?超级T#2,A#2,D>) A#2扩展对象在方法groupingBy中声明(Function<?超级T#2?扩展K>,Collector<?超级T#2,A#2,D>) D扩展对象的方法groupingBy(Function<?超级T#2?扩展K>,Collector<?超级T#2,A#2,D>) R#2扩展对象在方法flatMap(Function<??超级T#1?扩展Stream<?扩展R#2>>)
我做错什么了?
请注意,我最初的情况不是将数字分配给它们的倍数。实际上,我的组In有长值,列表包含自定义对象。但是当我把上面的例子解决后,我想我可以把它应用到我的案例中。我只想简单地描述一下这个问题。
发布于 2020-10-30 12:36:59
你是说像这样?
Map<Integer,List<Integer>> v = IntStream.range(2, 11).boxed()
.map(g -> IntStream.range(2, 41)
.boxed()
.filter(i -> i % g == 0)
.map(i -> new AbstractMap.SimpleEntry<>(g, i))
.collect(Collectors.groupingBy(AbstractMap.SimpleEntry::getKey,
Collectors.mapping(AbstractMap.SimpleEntry::getValue, Collectors.toList()))))
.flatMap(m -> m.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
https://stackoverflow.com/questions/64608357
复制相似问题