Frequency Map in Java 8+


Frequency Map in Java 8 or above can be created concisely with the help of Stream and Collectors.groupingBy() API.

A general method to count frequency of elements:

import java.util.*;
import java.util.function.*;
<T> Map<T, Long>  frequencyMap(Stream<T> elements) {
return elements.collect(
    HashMap::new, // can be skipped

Any streamable and countable collection can utilise the above method to count the frequency of elements.

Frequency Map of List Elements

A list can be converted to stream by calling stream().

List<String> words = Arrays.asList("hello", "hello", "mighty");

Frequency Map of Characters Array

An array of Character can be converted to Stream using

Character[] letters = {'a', 'b', 'b', 'c', 'c', 'c'};

Frequency Map of Characters from String

String characters can be converted to stream chars(). However, it returns intergers stream instead of charcters stream; Each integer needs to be converted back to character using maptoObj method as:

String aString = "abc"
frequencyMap(aString.chars().mapToObj(c -> (char) c));

Frequency Map of Integers Array or unboxed type

An array of unboxed typed elements can be converted to Stream using and calling boxed()

int [] numbers = {1, 2, 3};

See it in action →


Be Updated

Only articles are shared on Medium

This site uses third-party cookies to gather website usage and performance data.