JavaDeveloper
JavaDeveloper

Reputation: 5660

How to populate a map in Java 8?

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?

Upvotes: 3

Views: 1546

Answers (4)

Norbert Bicsi
Norbert Bicsi

Reputation: 1568

Here is another way

for (Character ch : chars) {
    inputStringCountMap.merge(ch, 1, (a, b) -> a+b);
}

Upvotes: 1

Anuj Vishwakarma
Anuj Vishwakarma

Reputation: 842

You can try something like this.

Map<Character,Integer> myFreq= new HashMap<>();
for (char ch : input.toCharArray()) {
    myFreq.put(ch, myFreq.getOrDefault(ch, 0) + 1);
}

Upvotes: 3

Joe C
Joe C

Reputation: 15704

If you're OK with a Map<Character, Long>, a grouping collector with a counting subcollector should do it:

Map<Character, Long> result = chars.stream().collect(
    Collectors.groupingBy(Function.identity(), Collectors.counting());

If you require the value type to be Integer, this can be done with a map collector:

Map<Character, Integer> result = chars.stream().collect(
    Collectors.toMap(Function.identity(), c -> 1, Integer::sum);

Upvotes: 5

Ruslan
Ruslan

Reputation: 6300

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

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

}

Upvotes: 11

Related Questions