我在Java中有以下数组:
int arr[] = {4,5,6};
我想将其转换为一个java.util.Map<K,V>
实例,该实例具有数组的索引作为键,索引处的值作为Map的值。像这样
0 = 4
1 = 5
2 = 6
我尝试了以下方法:
IntStream.range(0, arr.length)
.collect(Collectors.toMap(k -> k, k -> arr[k]));
但这会导致编译错误,例如:
Type mismatch: cannot convert from Collector<Object,capture#1-of ?,Map<Object,Object>> to Supplier<R>
和
The method collect(Supplier<R>, ObjIntConsumer<R>, BiConsumer<R,R>) in the type IntStream is not applicable for the arguments (Collector<Object,?,Map<Object,Object>>)
我在这里做错了什么?
我只是遍历所有索引,然后将它们映射到键和值,我哪里出错了?
尝试:
int arr[] = {4,5,6};
Map<Integer, Integer> resultMap = IntStream.range(0, arr.length).boxed()
.collect(Collectors.toMap(Function.identity(), k -> arr[k]));
resultMap.entrySet().forEach(entry -> System.out.println(entry.getKey() + " = " + entry.getValue()));
输出:
0 = 4
1 = 5
2 = 6
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句