将Java int数组转换为HashMap<Integer, Boolean>,使用IntStream

4
我需要对每个数组元素进行平方,并将此值作为键插入哈希映射中,值为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)));
2个回答

4
您可以将 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

@ugurdonmez 抱歉,已修复。 - Eran
由于已经存在映射步骤,因此额外的 boxed() 步骤是不必要的。此外,Boolean.valueOf(true) 已经过时:Arrays.stream(array).mapToObj(x -> x*x) .collect(Collectors.toMap(p -> p, p -> true)) - Holger

0
你可以使用一个简单的循环。
int [] array = {3, 1, 4, 6, 5};
HashMap<Integer, Boolean> map = new HashMap<Integer, Boolean>();

for(int i : array) {
   map.put(i*i, true);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接