How do you convert a collection like ["a", "b", "c"] to a map like {"a": 0, "b":1, "c":2} with the values being the order of iteration. Is there a one liner with streams and collectors in JDK8 for it? Old fashion way is like this:
Collection<String> col = apiCall();
Map<String, Integer> map = new HashMap<>();
int pos = 0;
for (String s : collection) {
map.put(s, pos++);
}
You can use AtomicInteger as index in stream:
Collection col = Arrays.asList("a", "b", "c");
AtomicInteger index = new AtomicInteger(0);
Map collectedMap = col.stream().collect(Collectors.toMap(Function.identity(), el -> index.getAndIncrement()));
System.out.println("collectedMap = " + collectedMap);
It you don't need a parallel stream you can use the length of the map as an index counter:
collection.stream().forEach(i -> map.put(i, map.size() + 1));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With