Collectors.groupingBy(功能,供应商,收集器)不接受lambda/看不到流式传输的值 [英] Collectors.groupingBy (Function, Supplier, Collector) doesn't accept lambda / dosen't see streamed values
问题描述
我尝试使用流和收集器对值进行分组. 我有要拆分的String列表.
I tried to group values using streams and Collectors. I have list of String which I have to split.
我的数据:
List<String> stringList = new ArrayList<>();
stringList.add("Key:1,2,3")
stringList.add("Key:5,6,7")
键是地图中的键, 1,2,3 是地图中的值
Key is a key in map and 1,2,3 are a values in map
首先,我尝试使用简单的toMap
First I have tried using simple toMap
Map<String, List<Integer>> outputKeyMap = stringList.stream()
.collect(Collectors.toMap(id -> id.split(":")[0],
id-> Arrays.stream(id.split(":")[1].split(",")).collect(Collectors.toList());
,但是它不能正常工作,因为它总是创建相同的密钥.所以我需要使用groupingBy
函数.
but it dosen't work because it always create the same key. So I need to use groupingBy
function.
Map<String, List<Integer>> outputKeyMap = stringList.stream().collect(groupingBy(id -> id.toString().split(":")[0],
TreeMap::new,
Collectors.mapping(id-> Arrays.stream(id.toString().split(":")[1].split(","))
.map(Integer::valueOf)
.collect(Collectors.toSet()))));
但是在此解决方案中,编译器看不到将值传递给lambda函数,而且我不为什么,因为Function
是第一个参数,同时也传递到Collectors.mapping
中.在此解决方案中,流不起作用.
But in this solution compiler dosen't see values passed into lambda functions, and I don't why because Function
is as first parameter, and also into Collectors.mapping
. In this solution stream doesn't work.
Collectors.groupingBy (Function<? super T, ? extends K> classifier,
Supplier<M> mapFactory,
Collector<? super T, A, D> downstream)
为什么groupingBy功能不起作用
我忘记在Collectors.mapping中添加Collectors.toSet()作为第二个参数.但是后来我收到Set in Set,所以这不是我想要的.应该使用flatMapping,但是它在Java9中.
I forgot to add Collectors.toSet() in Collectors.mapping as the second parameter. But then I receive Set in Set so it wasn't what am I looking for. There should be used flatMapping but it is in Java9.
Map<String, Set<Set<String>>> collect = stringList.stream()
.collect(groupingBy(id -> id.split(":")[0],
TreeMap::new,
Collectors.mapping(id-> Arrays.stream(id.toString().split(":")[1].split(","),
Collectors.toSet())