Java 流列表到索引映射

Java stream list to index map

如何从字符串列表中获取映射,其中索引是键,字符串是值?

如果我有这样一个列表

List<String> list = List.of("foo","bar","baz","doo");

我想要一个Map<Integer,String>

{0=foo, 1=bar, 2=baz, 3=doo}

当我执行以下操作时出现错误

static Map<Integer,String> mapToIndex(List<String> list) {
    return IntStream.range(0, list.size())
            .collect(Collectors.toMap(Function.identity(), i -> list.get(i)));
}

错误

Required type: int Provided: Object

当我将它转换为 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)));
}

我得到

'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>>)'

我错过了什么?

只需添加装箱即可将 ints 转换为 Integers

IntStream.range(0, list.size())
         .boxed()
         .collect(Collectors.toMap(Function.identity(), i -> list.get(i)));

IntStream doesn't have a collect() method taking a Collector as parameter, so you have to use 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));
}