Java Stream How to - Collect to ConcurrentMap








Question

We would like to know how to collect to ConcurrentMap.

Answer

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;
//from  ww  w  . j a v a 2 s . c  o m
public class Main {

    public static void main(String[] args) {
        List<String> strings = new LinkedList<>();
        strings.add("a");
        strings.add("B");
        strings.add("ab");
        strings.add("abc");
        strings.add("ABC");

        ConcurrentMap<Integer, List<String>> byLength = strings
                .parallelStream().collect(
                        Collectors.groupingByConcurrent(String::length));

        System.out.println(byLength);
    }
}

The code above generates the following result.