Java 8 List<T> into Map<T, (index)>

java, java-8, java-stream, lambda

Solution

You can use the following nasty trick, but it's not elegant, and not efficient at all on linked lists:

List<String> list = Arrays.asList("a", "b", "c");
Map<String, Integer> result = 
    IntStream.range(0, list.size())
             .boxed()
             .collect(Collectors.toMap(list::get, Function.identity()));

It's also less readable than the simple for loop, IMO. So I would stick to that.

Problem

Is there a convenient Java8 stream API way to convert from `List<T>` `to Map<T, (index)>`like below example: ``` List<Character> charList = "ABCDE".chars().mapToObj(e->(char)e).collect(Collectors.toList()); Map<Character, Integer> map = new HashMap<>(); for (int i = 0; i < charList.size(); i++) { map.put(charList.get(i), i); } ``` map = {A=0, B=1, C=2, D=3, E=4}

Original source

Related problems