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 chars in String

farenda 2016-11-19 0

Java interview question: In Java 8 count frequency of chars in a String. In this post we’ll show two implementations – using Map.merge() and Streams and Collectors.

foreach with Java 8 Map.merge()

The simplest way to count frequency of chars in a String is to use the standard foreach loop for char array traversal and doing counting with fantastic Map.merge() available since Java 8:

String s = "abcaba";
Map<Character, Integer> freqs = new HashMap<>();
for (char c : s.toCharArray()) {
    freqs.merge(c,                  // key = char
                1,                  // value to merge
                Integer::sum);      // counting
}
System.out.println("Frequencies:\n" + freqs);

Isn’t that cool? :-) Map.merge(key, value, BiFunction) is doing the tedious update of the Map if a char exists there or not.

The above code prints:

Frequencies:
{a=3, b=2, c=1}

Java 8 Stream and Collector

Another approach could be using Stream of chars and using some Collector to count and store values, but the solution is a bit cumbersome due to typing:

String s = "abcaba";
Map<Character, Integer> frequencies = s.chars().boxed()
        .collect(toMap(
                // key = char
                k -> Character.valueOf((char) k.intValue()),
                v -> 1,         // 1 occurence
                Integer::sum)); // counting
System.out.println("Frequencies:\n" + frequencies);

The String.chars() method returns IntStream of characters, so we have to box them to Integer to resolve type problems in Collector.

Frequencies:
{a=3, b=2, c=1}

References:

  • Java 8 Map.merge() explained
  • Check out other Java Tutorials
Share with the World!
Categories Java Tags java, java-util, java8
Previous: Java 8 count frequency of numbers/elements/objects
Next: Java 8 range of numbers

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
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.Ok