将整型列表转换为java8中的映射?

将整型列表转换为java8中的映射?,java,list,java-8,hashmap,type-conversion,Java,List,Java 8,Hashmap,Type Conversion,我可以从列表通过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

我可以从
列表
通过
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);
代码抛出此异常

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)

为什么?

使用
Integer::intValue
而不是
integers::get
,因为它希望参数类似于
ClassName::methodnametbecalledTogetTogetthedesiredValue

此外,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);
List integers=Arrays.asList(1,2,53,66,55,996989,99,33);
Map Map=integers.stream().distinct().collect(Collectors.toMap(Integer::intValue,Integer::intValue));
系统输出打印项次(map);

输出:{33=33,1=1,66=66,2=2,99=99,53=53,55=55,6989=6989}

你认为收集器是什么
toMap(integers::get,integers::get)
?你为什么这么认为?**::我认为方法引用会做到这一点,因为它会正确处理列表中的每个元素,如果我的假设是错误的,请检查我**尝试此映射Map=integers.stream().distinct().Map(p->p).collect(collector.toMap(Integer::intValue,Integer::intValue));使用map=integers.stream().distinct().collect(Collectors.toMap(Integer::intValue,Integer::intValue));因为toMap期望参数为ClassName::MethodNameToBecalledTogetthedesiredValues,所以您认为
.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);