如何使用 Java 中的 Stream 填充 HashMap<Long, Long>

How do I fill a HashMap<Long, Long> using a Stream in Java

我想使用 Java 中的流填充 HashMap<Long, Long>。但是,我没有做对。希望有人能帮忙。

我是这么想的:

HashMap<Long, Long>  mapLongs = LongStream
    .rangeClosed(1, 10)
    .collect(Collectors.toMap(x -> x, x -> getSquare(x)));

其中getSquare是一个简单的函数returns平方,例如:

long getSquare(long x) {
    return x * x;
}

但是,我收到一条错误消息,提示无法将 getSquare() 应用于对象。当我尝试将 x 转换为一个对象时,我得到一个错误:

no instance(s) of type variable(s) A, K, T, U exist so that Collector> conforms to Supplier

底线:我卡住了。

此外(显然),我正在尝试做一些比用平方值填充地图更复杂的事情...

只需确保您的直播是 boxed

Map<Long, Long> mapLongs = LongStream  // programming to interface 'Map'
        .rangeClosed(1, 10)
        .boxed()
        .collect(Collectors.toMap(x -> x, x -> getSquare(x))); // can use method reference as well