Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert List to Map with indexes using stream - Java 8?

I've created method whih numerating each character of alphabet. I'm learning streams(functional programming) and try to use them as often as possible, but I don't know how to do it in this case:

private Map<Character, Integer> numerateAlphabet(List<Character> alphabet) {     Map<Character, Integer> m = new HashMap<>();     for (int i = 0; i < alphabet.size(); i++)         m.put(alphabet.get(i), i);     return m; } 

So, how to rewrite it using streams of Java 8?

like image 963
Letfar Avatar asked Oct 15 '15 01:10

Letfar


People also ask

How do you index a Stream Map?

Create an AtomicInteger for index. Get the Stream from the array using Arrays. stream() method. Map each elements of the stream with an index associated with it using map() method where the index is fetched from the AtomicInteger by auto-incrementing index everytime with the help of getAndIncrement() method.

What is flatMap in Java Stream?

Stream flatMap(Function mapper) returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Stream flatMap(Function mapper) is an intermediate operation. These operations are always lazy.


1 Answers

Avoid stateful index counters like the AtomicInteger-based solutions presented in other answers. They will fail if the stream were parallel. Instead, stream over indexes:

IntStream.range(0, alphabet.size())          .boxed()          .collect(toMap(alphabet::get, i -> i)); 

Above assumes that the incoming list is not supposed to have duplicate characters since it's an alphabet. If you have possibility of duplicate elements then multiple elements will map to same key and then you need to specify merge function. For example you can use (a,b) -> b or (a,b) ->a as the third parameter to toMap method.

like image 184
Misha Avatar answered Sep 27 '22 21:09

Misha