Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 lambda: convert Collection to Map of element, iteration position

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++);
    }
like image 341
danial Avatar asked Jul 30 '14 15:07

danial


2 Answers

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);
like image 125
K. Gol Avatar answered Oct 04 '22 13:10

K. Gol


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));
like image 37
maba Avatar answered Oct 04 '22 14:10

maba