Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Java 8 count frequency of numbers/elements/objects

farenda 2016-11-18 0

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:

  • Check out other cool Java Tutorials!
Share with the World!
Categories Java Tags java, java-util, java8
Previous: Java 8 List to Map
Next: Java 8 count frequency of chars in String

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2021

sponsored