Learnitweb

Count the Frequency of Each Element in a List

Approach 1 — Using groupingBy and counting

List<String> items = List.of("a", "b", "a", "c", "b", "a");

Map<String, Long> freq = items.stream()
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

System.out.println(freq);

Approach 2 — Using toMap with a Merge Function

Map<String, Integer> freq2 = items.stream()
    .collect(Collectors.toMap(Function.identity(), v -> 1, Integer::sum));

System.out.println(freq2);

Explanation:

  • groupingBy + counting is idiomatic and concise for frequency maps.
  • toMap with a merge function is more flexible and allows custom accumulation logic.