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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…