-1

I want to transform a list of String to a map, where the key of map is a simple increment.

For example:

List<String> result = new ArrayList<String>();
result.add("hello");
result.add("Java");

Pretend result:

Map<Integer, String> mapOfList;
map(1, "Hello");
map(2, "Java");

Try:

AtomicInteger atomic=new AtomicInteger(0);
mapOfList=result.stream().collect(atomic.incrementAndGet(), s -> s);
Goldbones
  • 1,317
  • 2
  • 18
  • 45

1 Answers1

-1

Try this

result.stream()
    .collect(Collectors.toMap(element -> atomic.incrementAndGet(), Function.identity());
user7
  • 15,765
  • 4
  • 38
  • 68
  • Functions should generally be stateless, although documentation doesn't say it explicitly in this case. `atomic` is effectively a state of a `keyMapper` function here. If you changed it to parallel stream it would mess up the ids. – Jaroslaw Pawlak Sep 13 '18 at 16:53