【发布时间】:2020-07-08 17:24:18
【问题描述】:
我在 Java 中有以下数组:
int arr[] = {4,5,6};
我想将它转换为java.util.Map<K,V> 实例,该实例将数组的索引作为键,将索引处的值作为映射的值。像这样,
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>>)
我在这里做错了什么?
我只是检查所有索引,然后将它们映射到我哪里出错的键和值?
【问题讨论】:
-
这能回答你的问题吗? Java 8 int array to map
-
IntStream只有一个collect方法:docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/…。尝试将其映射到Stream<Integer>,如下所示:IntStream.range(0, arr.length).mapToObj(Integer::valueOf).collect(Collectors.toMap(k -> k, k -> Integer.valueOf(arr[k.intValue()])));。 -
尝试通过使用 IntStream#boxed 来使用整数流。
标签: java collections java-8 java-stream