我可以从Map<Integer, Integer>
到List
语句构建for
,如此
List<Integer> integers = Arrays.asList(1, 2, 53, 66, 55, 99, 6989, 99, 33);
Map<Integer, Integer> map = new HashMap<>();
for (Integer integer : integers) {
map.put(integer, integer);
}
System.out.println(map);
但是当我尝试使用流
时map = integers.stream().distinct().map(p -> p).collect(Collectors.toMap(integers::get, integers::get));
代码抛出此异常
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 53
at java.util.Arrays$ArrayList.get(Unknown Source)
at java.util.stream.Collectors.lambda$toMap$58(Unknown Source)
at java.util.stream.ReduceOps$3ReducingSink.accept(Unknown Source)
at java.util.stream.ReferencePipeline$3$1.accept(Unknown Source)
at java.util.stream.DistinctOps$1$2.accept(Unknown Source)
at java.util.Spliterators$ArraySpliterator.forEachRemaining(Unknown Source)
at java.util.stream.AbstractPipeline.copyInto(Unknown Source)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(Unknown Source)
at java.util.stream.AbstractPipeline.evaluate(Unknown Source)
at java.util.stream.ReferencePipeline.collect(Unknown Source)
at com.me.lamda.LamdaOps.main(LamdaOps.java:30)
为什么呢?
答案 0 :(得分:0)
使用Integer::intValue
代替integers::get
,因为它希望参数类似于ClassName::methodNameToBeCalledToGetTheDesiredValue
此外,map(p-> p)在这里是多余的,因为您没有将值映射到其他内容。
试试这个
List<Integer> integers= Arrays.asList(1,2,53,66,55,99,6989,99,33);
Map<Integer, Integer> map = integers.stream().distinct().collect(Collectors.toMap(Integer::intValue, Integer::intValue));
System.out.println(map);
输出:{33 = 33,1 = 1,66 = 66,2 = 2,99 = 99,53 = 53,55 = 55,6989 = 6989}