使用 java8 将列表转换为地图
convert list to map using java8
我有一个数组列表
List<Integer> h = Arrays.asList(1,2,3,4,5,6);
我想过滤偶数,然后用键将它们存储在映射中,键是从 1 开始的唯一数字,值是使用 java8
过滤后的值
输出1-2 2-4 3-6
我将在 collect
中使用过滤器和 Collectors.toMap()
Map<Integer,Integer> j = h.stream().filter(fe->fe%2==0).collect(Collectors.toMap(?,?));
输出结果是什么?
类似的东西
List<Integer> h = Arrays.asList(1,2,3,4,5,6);
AtomicInteger f = new AtomicInteger(0);
Map<Integer,Integer> j = h.stream()
.filter(fe-> fe%2==0)
.collect(Collectors.toMap(fs -> f.incrementAndGet(), fs -> fs));
我还没有测试过,也许这不是最好的主意,但如果你必须使用 Collectors.toMap,也许下面的方法可以工作
Map<Integer,Integer> j = h.stream()
.filter(fe->fe%2==0)
.collect(Collectors.toMap(i ->{
return h.stream().filter(fe->fe%2==0).collect(Collectors.toList()).indexOf(i);
},Function.identity()));
我有一个数组列表
List<Integer> h = Arrays.asList(1,2,3,4,5,6);
我想过滤偶数,然后用键将它们存储在映射中,键是从 1 开始的唯一数字,值是使用 java8
过滤后的值输出1-2 2-4 3-6
我将在 collect
中使用过滤器和Collectors.toMap()
Map<Integer,Integer> j = h.stream().filter(fe->fe%2==0).collect(Collectors.toMap(?,?));
输出结果是什么?
类似的东西
List<Integer> h = Arrays.asList(1,2,3,4,5,6);
AtomicInteger f = new AtomicInteger(0);
Map<Integer,Integer> j = h.stream()
.filter(fe-> fe%2==0)
.collect(Collectors.toMap(fs -> f.incrementAndGet(), fs -> fs));
我还没有测试过,也许这不是最好的主意,但如果你必须使用 Collectors.toMap,也许下面的方法可以工作
Map<Integer,Integer> j = h.stream()
.filter(fe->fe%2==0)
.collect(Collectors.toMap(i ->{
return h.stream().filter(fe->fe%2==0).collect(Collectors.toList()).indexOf(i);
},Function.identity()));