Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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}

like image 614
Daniel Hári Avatar asked Sep 05 '25 17:09

Daniel Hári


1 Answers

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.

like image 124
JB Nizet Avatar answered Sep 10 '25 14:09

JB Nizet