I consider it a bit hacky because it only solves the problem of effectively final variable. Since it is a special ThreadSafe version it might introduce some overhead. Pure stream solution in the answer by Samuel Philipp might better fit your needs.

AtomicInteger is thread-safe and it might introduce some overhead. I consider it a bit hacky. I think that solution by SamuelPhilipp is better than this. Also notice that it only solves the problem of your variable not being effectively final.
– michalkAug 24 at 13:18

3

The irony is that this bears the costs of a thread safe operation while not being thread safe, due to relying on the processing order. A clean solution without these problems, is possible…
– HolgerAug 26 at 9:25

You create an IntStream from 0 to list.size() - 1 (IntStream.range() excludes the last value from the stream) and map each index to the value in your list. The advantage of this solution is, that it will also work with parallel streams, which is not possible with the use of an AtomicInteger.

If there are duplicates in the list, the index of the first occurence of the element will be added in the final map. Also to resolve the merge error in the map during a key collision we need to ensure that there is a merge function supllied to the toMap(keyMapper, valueMapper, mergeFunction)

Using indexOf is not quite a good idea, because of two reasons: It as a worse performance for large lists as it has a time complexity of O(n) (for an ArrayList) and if the list contains a value more than one time you get a wrong result, as indexOf only returns the first index, so you will overwrite the first value.
– Samuel PhilippAug 24 at 13:23

1

@SamuelPhilipp what you is correct, even I have thought of that so this solution is applicable for a small list. But OP asked specifically that "Is there a simple way to map elemnts of a stream to their indices", so OP wants the actual indices from the list. And yes if there are duplicates the last occurence of the element's index will be added in the map.
– Fullstack GuyAug 24 at 13:27

Thank you for adding one mor approach. But this produce a java.lang.IllegalStateException: Duplicate key one if I add a duplicate string 'one', but will work if the list contains unique elements.
– nopensAug 24 at 13:29

1

@nopens yes I forgot to add the mergeFunction in the last parameter of toMap which resolves the merge error for duplicate key
– Fullstack GuyAug 24 at 13:34