【发布时间】:2018-07-10 03:13:59
【问题描述】:
我可以像这样通过for 语句从List 构造一个Map<Integer, Integer>
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)
为什么?
【问题讨论】:
-
你认为
Collectors.toMap(integers::get, integers::get)是做什么的?你为什么这么认为? -
** :: 我认为方法引用会这样做,因为它会使列表中的每个元素都正确,如果我的假设是错误的,请纠正我**
-
试试这个 Map
map = integers.stream().distinct().map(p -> p).collect(Collectors.toMap(Integer::intValue, Integer:: intValue)); -
使用 map = integers.stream().distinct().collect(Collectors.toMap(Integer::intValue, Integer::intValue));因为 toMap 期望参数为 ClassName::methodNameToBeCalledToGetTheDesiredValue
-
就此而言,您认为
.map(p -> p)会做什么?
标签: java list java-8 hashmap type-conversion