[英]Java stream list to index map
How can I get a map from a list of strings, where the index is the key and the string is the value?如何从字符串列表中获取 map,其中索引是键,字符串是值?
If I have such a list如果我有这样一个列表
List<String> list = List.of("foo","bar","baz","doo");
I want to get a Map<Integer,String>
like我想得到一个
Map<Integer,String>
类的
{0=foo, 1=bar, 2=baz, 3=doo}
When I do the following I get an error当我执行以下操作时出现错误
static Map<Integer,String> mapToIndex(List<String> list) {
return IntStream.range(0, list.size())
.collect(Collectors.toMap(Function.identity(), i -> list.get(i)));
}
error错误
Required type: int Provided: Object
所需类型:int 提供:Object
When I cast it to int or Integer当我将它转换为 int 或 Integer
static Map<Integer,String> mapToIndex(List<String> list) {
return IntStream.range(0, list.size())
.collect(Collectors.toMap(Function.identity(), i -> list.get((Integer) i)));
}
i get我明白了
'collect(java.util.function.Supplier, java.util.function.ObjIntConsumer, java.util.function.BiConsumer<R,R>)' in 'java.util.stream.IntStream' cannot be applied to '(java.util.stream.Collector<java.lang.Object,capture<?>,java.util.Map<java.lang.Object,java.lang.String>>)'
'收集(java.util.function.Supplier,java.util.function.ObjIntConsumer,java.util.function.BiConsumer <R,R>)'在'java.util.8849488不能应用于'java.util.8849488'中.util.stream.Collector<java.lang.Object,capture<?>,java.util.Map<java.lang.Object,java.lang.String>>)'
What I am missing?我缺少什么?
IntStream
doesn't have a collect()
method taking a Collector
as parameter, so you have to use boxed()
to convert it to a Stream<Integer>
: IntStream
没有将Collector
作为参数的collect()
方法,因此您必须使用boxed()
将其转换为Stream<Integer>
:
static Map<Integer, String> mapToIndex(List<String> list) {
return IntStream.range(0, list.size()).boxed().collect(Collectors.toMap(Function.identity(), list::get));
}
Just add boxing to convert int
s to Integer
s只需添加装箱即可将
int
转换为Integer
s
IntStream.range(0, list.size())
.boxed()
.collect(Collectors.toMap(Function.identity(), i -> list.get(i)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.