Java Programming Tutorials

Java programming tutorials with many code examples!

Java 8 count frequency of numbers/elements/objects

In Java 8 count frequency of numbers/elements/objects. You may encounter this problem on Java job interviews. Here we implement it using Java 8 Collectors.

Helper method to generate range of numbers

Just to create a bunch of random numbers we’ll use standard java.util.Random class and pass it to IntStream.generate():

private static List<Integer> randomNumbers(int n, int bound) {
    Random rand = new Random();
    return IntStream
            .generate(() -> rand.nextInt(bound))
            .limit(n)
            .boxed()
            .collect(Collectors.toList());
}

Count frequency of numbers

In the following code we count frequency of numbers (let’s say they are grades). To do that we’re going to use Java 8 Stream to pass every number to Collector.toMap(keyMapper, valueMpper, mergeFunction), which will create a java.util.Map for us:

List<Integer> grades = randomNumbers(1000, 10);

Map<Integer, Integer> frequencies = grades.stream()
        .collect(toMap(identity(), v -> 1, Integer::sum));
System.out.println("Frequencies:\n" + frequencies);

What the toMap() Collector parts are:

  • Function<? super T,? extends K> keyMapper:
    Receives a value from the Stream and returns what should be used as map key. In our example we want to use counted numbers as map keys, so we use identity() method from java.util.function.Function to return it as is.
  • Function<? super T,? extends U> valueMapper:
    Receives the same value from the stream, but should return a thingy that should be stored as a value inside resulting map. We just count the items, so return 1.
  • BinaryOperator<U> mergeFunction:
    This is the real counting function. It is called every time when keyMapper returns a key that is already in the map. This function is for resolving this conflict. The mergeFunction takes new value and old value as parameters and, in our case, just adds them – the new value is always 1 and the old value is current frequency of number for current key.

Sample output from running the above code:

Frequencies:
{0=99, 1=109, 2=85, 3=83, 4=110, 5=105, 6=97, 7=105, 8=104, 9=103}

References:

Share with the World!