【问题标题】:Convert list of type Integer to map in java8? [duplicate]将整数类型列表转换为java8中的映射? [复制]
【发布时间】: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 -&gt; p) 会做什么?

标签: java list java-8 hashmap type-conversion


【解决方案1】:

使用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}

【讨论】:

猜你喜欢
  • 2021-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-25
  • 1970-01-01
相关资源
最近更新 更多