How can one idiomatically enumerate a Stream<T>
which maps each T
instance to a unique integer using Java 8 stream methods (e.g. for an array T[] values
, creating a Map<T,Integer>
where Map.get(values[i]) == i
evaluates to true
)?
Currently, I'm defining an anonymous class which increments an int
field for use with the Collectors.toMap(..)
method:
private static <T> Map<T, Integer> createIdMap(final Stream<T> values) {
return values.collect(Collectors.toMap(Function.identity(), new Function<T, Integer>() {
private int nextId = 0;
@Override
public Integer apply(final T t) {
return nextId++;
}
}));
}
However, is there not a more concise/elegant way of doing this using the Java 8 stream API? — bonus points if it can be safely parallelized.