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}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With