1. Overview
In this tutorial, We'll learn how to find the character most appeared in the string in java.
In the previous tutorial explained how to remove or delete a specific character from string in java 8?
Finding most frequently occurring character from string can be solved in many ways. But, we will present the most used and efficient solutions.
At the end, how to solve this problem using java 8 stream api methods.
2. Java - Find Most Repeated Character In String Using HashMap
First, Let us solve this problem using collection api HashMap class.
In this approach, Create the HashMap instance using new keyword.
Convert the string to char array using to toCharArray(). Then iterate the char array over the for loop. Take each character and add it to the HashMap with the value as current number of instances.
If the character is already present in the HashMap then increment the existing value by 1 and update the the HashMap.
Like this, perform the steps till last character of the string. By end, hash map contains the character which is most repeated.
Next, get the max of values of HashMap using Collections.max() method.
Now, get the character from HashMap which value is matching to the max value from above step.
Look at the below code.
package com.javaprogramto.programs.strings.find.most; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.lang3.tuple.Pair; public class FindMostRepeatedCharacterInStringExample { public static void main(String[] args) { String input = "hello world"; Pair<Character, Integer> maxCharCountPair = getMostRepeatedCharacterFromString(input); System.out.println("Input string : " + input); System.out.println(maxCharCountPair.getKey() + " is the most repeated character for " + maxCharCountPair.getValue() + " times."); } private static Pair<Character, Integer> getMostRepeatedCharacterFromString(String input) { Map<Character, Integer> countMap = new HashMap<>(); char[] chars = input.toCharArray(); // storing the char and its count in the hashmap for (char ch : chars) { if (!Character.isWhitespace(ch)) { Integer currentCount = countMap.get(ch); if (currentCount == null) { countMap.put(ch, 1); } else { countMap.put(ch, ++currentCount); } } } // getting the max count from counter map. Integer maxCharacterCount = Collections.max(countMap.values()); char maxCharacter = Character.MIN_VALUE; // getting the max occurred character. for (Entry<Character, Integer> entry : countMap.entrySet()) { if (entry.getValue() == maxCharacterCount) { maxCharacter = entry.getKey(); } } return Pair.of(maxCharacter, maxCharacterCount); } }
Output:
Input string : hello world l is the most repeated character for 3 times.
The above program compiles and run without any errors. But this is lengthy program using HashMap.
Here, we have captured the most repeated character and its count in Pair object. Most repeated char and its value is retrieved from getKey() and getValue() from Pair instance.
3. Java - Find Most Repeated Character In String Using ASCII sized Array
You might have observed that there are many loops and getting the max from HashMap and its traversals. Because of many operations, the execution may take longer for the larger inputs.
Now, we'll see another efficient approach using ASCII codes.
First, we will initialize the new empty int array with size of 256 which is the no of ASCII codes.
The same concept is used in solving the problem to find the first non repeated character from string.
look at the below program.
package com.javaprogramto.programs.strings.find.most; import org.apache.commons.lang3.tuple.Pair; public class FindMostRepeatedCharacterInStringExample2 { public static void main(String[] args) { String input = "hello world"; Pair<Character, Integer> maxCharCountPair = getMostRepeatedCharacterFromString(input); System.out.println("Input string : " + input); System.out.println(maxCharCountPair.getKey() + " is the most repeated character for " + maxCharCountPair.getValue() + " times."); } private static Pair<Character, Integer> getMostRepeatedCharacterFromString(String input) { int[] asciiIntArray = new int[256]; char[] chars = input.toCharArray(); int mostAppearanceCount = 0; char mostAppearedChar = Character.MIN_VALUE; // storing the char and its count in the hashmap for (char ch : chars) { if (!Character.isWhitespace(ch)) { int asciiCode = (int) ch; asciiIntArray[asciiCode]++; if (asciiIntArray[asciiCode] > mostAppearanceCount) { mostAppearanceCount = asciiIntArray[asciiCode]; mostAppearedChar = ch; } } } return Pair.of(mostAppearedChar, mostAppearanceCount); } }
This program also produces the same output and this is an optimized logic. Works extremely well for large sized inputs.
4. Java 8 Solution To Find Most Repeated Character In String
The last solution, we will learn using java 8 functional style programming.
Using java 8, this problem can be solved in the single line but for the understanding purpose, we are putting into multiple lines.
Look at the below java 8 sample code.
package com.javaprogramto.programs.strings.find.most; import java.util.Map; import java.util.stream.Collectors; import org.apache.commons.lang3.tuple.Pair; public class FindMostRepeatedCharacterInStringExample3 { public static void main(String[] args) { String input = "hello world"; Pair<Character, Long> maxCharCountPair = getMostRepeatedCharacterFromString(input); System.out.println("Input string : " + input); System.out.println(maxCharCountPair.getKey() + " is the most repeated character for " + maxCharCountPair.getValue() + " times."); } private static Pair<Character, Long> getMostRepeatedCharacterFromString(String input) { return input.chars() .filter(c -> Character.isWhitespace(c) == false) // ignoring space .mapToObj(c -> (char) c) .collect(Collectors.groupingBy(c -> c, Collectors.counting())) .entrySet() .stream() .max(Map.Entry.comparingByValue()) .map(p -> Pair.of(p.getKey(), p.getValue())) .orElse(Pair.of(Character.MIN_VALUE, -1L)); } }
This program also generates the same output.
5. Conclusion
In this article, we've seen how to find the most appeared character from string in java in different ways.
No comments:
Post a Comment
Please do not add any spam links in the comments section.