Home > Net >  Java stream list to index map
Java stream list to index map

Time:04-29

How can I get a map from a list of strings, where the index is the key and the string is the value?

If I have such a list

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

I want to get a Map<Integer,String> like

{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

When I cast it to int or 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>>)'

What I am missing?

CodePudding user response:

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> :

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

CodePudding user response:

Just add boxing to convert ints to Integers

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