如何从LongStream创建地图

fwe*_*end 3 java java-8 java-stream

假设我有一个LongStream范围,我想将长值放在一个映射中作为键,一个函数结果作为值.

例如:

Map<Long, Long> m = LongStream.range(1, 20) ...

long someFunction(long n) {
  return n * n;
}
Run Code Online (Sandbox Code Playgroud)

然后,地图应包含映射到这些值的平方的1到20.我看过收集和收藏家,但我似乎找不到合适的解决方案.

编辑:我有以下工作.

Map<Long, Long> map = LongStream
        .range(1, 20)
        .boxed()
        .collect(toMap(identity(), AmicablePairs::properDivsSum));
Run Code Online (Sandbox Code Playgroud)

除了没有调用盒装之外,我还得到了函数的调用符号错误.我当然不能使用双冒号,因为我需要传递一个参数.

Bor*_*der 8

您需要设置值:

Map<Long, Long> m = LongStream.range(1, 20)
        .boxed()
        .collect(toMap(identity(), this::magic));
Run Code Online (Sandbox Code Playgroud)

有点难看,是的.但Java集合仅支持对象.

  • `.mapToObj(i -&gt; i)` 等价于 `.boxed()` (2认同)