【发布时间】:2018-10-05 03:09:17
【问题描述】:
我有一个整数数组,我想将其转换为地图。我已经尝试使用下面的代码。
但是当我尝试使用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() 函数将数组转换为映射?
【问题讨论】:
标签: java-8 java-stream collectors