• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
Clean Programmer

Clean Programmer

Programming & DevOps Resources

  • Home
  • Library
  • About
  • Contact

Calculate Character Frequency In String Using Java Stream API

October 13, 2018 Monzurul Haque Shimul

There are many ways to count the number of occurrences of a character in a String in Java. In this article, we’re going to see how we can check frequency of characters inside a string by using Java Stream API.

public Map<String, Long> countChars(String input) {
    Map<String, Long> frequentChars = Arrays.stream(input.toLowerCase().split(""))
            .collect(Collectors.groupingBy(c -> c, Collectors.counting()));
    frequentChars.forEach((k, v) -> System.out.println(k + ":" + v));
    return frequentChars;
}

Here, I have converted the input string to lower case and split it into an array and then created a stream from the string array of characters from the input string converting it to lower case and then applied the Collectors.counting() method inside the Stream.collect() to convert it to a Map<String, Long> where keys contain the characters and the values contain the frequency of it in the input string.

Collectors is an implementations of Collector that implement various useful reduction operations, such as accumulating elements into collections, summarizing elements according to various criteria, etc. Collectors.counting() returns a Collector accepting elements of type T that counts the number of input elements.

Java java stream api

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Categories

  • Apache Kafka
  • Druid
  • Git
  • Java
  • Java EE
  • Redis
  • Spring
  • Uncategorized
  • Weblogic
  • Wildfly

Featured Posts

Loading data into Druid from TSV file

Deploy applications to a remote WildFly server using jboss-cli

Deploy applications to WildFly server using wildfly maven plugin

How to remotely connect to WildFly application server

Git Alias: Make your Git experience simpler, easier, faster and clean

Tags

bash bitbucket cassandra cloudserver curl docker druid.io eclipselink ejb git imply.io java java-ee jaxws jboss jboss-cli jdbc jdk jms kafka maven minio mssql mysql ojdbc oracle postgresql redis rest rest-template S3 scality sdk sdkman soap spring sqlserver stream stream api weblogic web services wildfly wsdl zenko zookeeper

Archives

  • January 2019
  • December 2018
  • November 2018
  • October 2018
  • September 2018
  • August 2018
  • July 2018
  • June 2018
  • May 2018

Copyright © 2019 · CLEAN PROGRAMMER

  • Privacy Policy
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.OKNoRead more
Revoke Cookies