我需要对每个数组元素求平方,然后将一个条目插入到 hashmap 中,这个值作为键,true 作为值。我试过那样做,但我无法修复它。
int [] array = {3, 1, 4, 6, 5};
HashMap<Integer, Boolean> map = IntStream.of(array)
.map(x -> x*x)
.collect(Collectors.toMap(p -> Integer.valueOf(p), Boolean.valueOf(true)));
最佳答案
您可以 box
IntStream
并继续 Stream<Integer>
:
Map<Integer, Boolean> map = IntStream.of(array)
.map(x -> x*x)
.boxed()
.collect(Collectors.toMap(p -> p, p -> Boolean.valueOf(true)));
请注意 Collectors.toMap
返回 Map
, 不是 HashMap
.
关于Java int 数组到 HashMap<Integer, Boolean> 和 IntStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38252515/