Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

If I have such a list

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{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?

>Solution :

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));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading