How to populate a map in Java 8?

JavaDeveloper :
private static Map<Character, Integer> populateMap(List<Character> chars) {
    final Map<Character, Integer> inputStringCountMap  = new HashMap<Character, Integer>();
    for (Character ch : chars) {
        int val = 0;
        if (inputStringCountMap.containsKey(ch)) {
            val = inputStringCountMap.get(ch);
        }
        inputStringCountMap.put(ch, val + 1);
    }

    return inputStringCountMap;
}


The above function simply populates the Map with the count of each char.
Is there a shorter / cleaner way to do this in Java 8?

Ruslan :
 private static Map<Character, Long> populateMap(List<Character> chars) {

    return chars.stream()
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=84369&siteId=1