我有一个整数数组,我想将其转换为 map 。我尝试过使用下面的代码。
但是当我尝试使用以下格式使用 Collectors.toMap()
时,它不允许映射数组。
代码 1:正在运行
int arr1[] = {-5, 15, 25, 71, 63};
Map<Integer, Integer> hm = new HashMap<Integer, Integer>();
IntStream.range(0, arr1.length).forEach(i -> hm.put(i, arr1[i]));
System.out.println(hm);
代码 2:它不起作用
Map<Integer, Integer> hm1=IntStream.range(0, arr1.length).collect(Collectors.toMap(i->i,i->arr1[i]));
谁能解释一下如何使用Collectors.toMap()
函数将数组转换为映射?
最佳答案
我认为这里的问题是 IntStream
正在生成原始整数流。尝试在流到达收集器之前将其装箱:
hm = IntStream.range(0, arr1.length).boxed().collect(Collectors.toMap(i->i,i->arr1[i]));
for (Map.Entry<Integer, Integer> entry : hm.entrySet()) {
System.out.println("(" + entry.getKey() + ", " + entry.getValue() + ")");
}
(0, -5)
(1, 15)
(2, 25)
(3, 71)
(4, 63)
Demo
关于java-8 - 如何使用流将一维整数数组转换为映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52657850/