In this article, we will count and print number of repeated character occurrences in a String i.e.;
1. Counting & printing in a String :
- Number of repeated character occurrences
- Along with its count
Note:- Same example is implemented using Java 1.8 version and Stream, check Java 8 – Count and print number of repeated character occurrences in a String
1.1 Steps for counting repeated character occurrences :
- Create empty HashMap of type Character & Integer
- Convert String into character[] array using toCharArray() method of String class
- Iterate through character[] array
- Leave blank spaces in between 2 words in a String sentence
- Check whether particular character present in the HashMap using containsKey(k) method of Map interface
- If it contains, then increase the count value by 1 using put(K, V) method of Map interface
- Otherwise insert using put() method of Map with count value as 1
- Get keySet() for iterating through Map
- Finally, print character[] array using for-each loop
- Code sorting logic for printing count value in descending order using Comparator interface
- Again print after sorting
ReadCountPrintRepeatedCharacterOccurencesInString.java
package in.bench.resources.count.print.occurences;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class ReadCountPrintRepeatedCharacterOccurencesInString {
public static void main(String[] args) {
// sample test string
String testStr = "Spring and Hibernate";
// invoke to count & print for supplied file
countAndPrintRepeatedCharacterOccurences(testStr);
}
/**
* this method is used
* to count number repeated word occurrences
* @param fileName
*/
public static void countAndPrintRepeatedCharacterOccurences(
String strContent) {
// Step 1: create Map of Character-Integer
Map<Character, Integer> mapOfRepeatedChar =
new HashMap<Character, Integer>();
// Step 2: convert String into character-array
// using toCharArray() method
char[] chArray = strContent.toCharArray();
// Step 3: iterate through char[] array
for(char ch : chArray) {
// Step 4: leave spaces
if(ch != ' '){
// Step 5: check
// whether Map contains particular character
if(mapOfRepeatedChar.containsKey(ch)){
// Step 6: If contains,
// increase count value by 1
mapOfRepeatedChar.put(ch,
mapOfRepeatedChar.get(ch) + 1);
}
else {
// Step 7: otherwise, make a new entry
mapOfRepeatedChar.put(ch, 1);
}
}
}
System.out.println("Before sorting : \n");
System.out.println("Char" + "\t" + "Count");
System.out.println("====" + "\t" + "=====");
// Step 8: get keySet() for iteration
Set<Character> character = mapOfRepeatedChar.keySet();
// Step 9: print word along with its count
for(Character ch : character) {
System.out.println(ch
+ "\t" + mapOfRepeatedChar.get(ch));
}
// Step 10: Sorting logic by invoking sortByCountValue()
Map<Character, Integer> wordLHMap = sortByCountValue(
mapOfRepeatedChar);
System.out.println("\n\nAfter sorting"
+ " in descending order of count : \n");
System.out.println("Char" + "\t" + "Count");
System.out.println("====" + "\t" + "=====");
// Step 11: Again print after sorting
for(Map.Entry<Character, Integer> entry :
wordLHMap.entrySet()){
System.out.println(entry.getKey()
+ "\t" + entry.getValue());
}
}
/**
* this method sort acc. to count value
* @param mapOfRepeatedWord
* @return
*/
public static Map<Character, Integer> sortByCountValue(
Map<Character, Integer> mapOfRepeatedWord) {
// get entrySet from HashMap object
Set<Map.Entry<Character, Integer>> setOfWordEntries =
mapOfRepeatedWord.entrySet();
// convert HashMap to List of Map entries
List<Map.Entry<Character, Integer>> listOfwordEntry =
new ArrayList<Map.Entry<Character, Integer>>(
setOfWordEntries);
// sort list of entries using Collections.sort(ls, cmptr);
Collections.sort(listOfwordEntry,
new Comparator<Map.Entry<Character, Integer>>() {
@Override
public int compare(Entry<Character, Integer> es1,
Entry<Character, Integer> es2) {
return es2.getValue().compareTo(es1.getValue());
}
});
// store into LinkedHashMap for maintaining insertion
Map<Character, Integer> wordLHMap =
new LinkedHashMap<Character, Integer>();
// iterating list and storing in LinkedHahsMap
for(Map.Entry<Character, Integer> map : listOfwordEntry){
wordLHMap.put(map.getKey(), map.getValue());
}
return wordLHMap;
}
}
Output:
Before sorting :
Char Count
==== =====
p 1
a 2
r 2
b 1
S 1
d 1
t 1
e 2
g 1
H 1
i 2
n 3
After sorting in descending order of count :
Char Count
==== =====
n 3
a 2
r 2
e 2
i 2
p 1
b 1
S 1
d 1
t 1
g 1
H 1
Note: Stop at Step 9, if there is no business requirements for sorting either way (ascending or descending)
2. Reading from file in Java 1.7 version :
- In the above example, we counted repeated words from String content
- Similarly, we can read file from local drive location and count number of repeated words
- While doing so, we need to provide catch block with FileNotFoundException and IOException for exception raised, as we are dealing with files
- We will use try-with-resources statement introduced in Java 1.7 version, as it handles automatic resource management (ARM) implicitly i.e.; auto-closing of opened resources without explicit closing inside finally block after necessary null-safety checks
- Thus, it improves readability of the code by reducing number of lines of code
Sample text file:
ReadPrintCharFromFileInJava7.java
package in.bench.resources.count.print.occurences;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class ReadPrintCharFromFileInJava7 {
public static void main(String[] args) {
// invoke to count & print for supplied file
countAndPrintRepeatedCharacterOccurences("D://WORKSPACE/"
+ "TEST_WORKSPACE/Java_8_Project/BRN2.txt");
}
/**
* this method is used
* to count number repeated word occurrences
* @param fileName
*/
public static void countAndPrintRepeatedCharacterOccurences(
String fileName) {
// local variables
String line = "";
// Step 1: create Map of Character-Integer
Map<Character, Integer> mapOfRepeatedChar =
new HashMap<Character, Integer>();
// Step A: Read file using try-with-resources statement
try(BufferedReader bufferedReader =
new BufferedReader(new FileReader(fileName))) {
// Step B: Read line from file
while ((line = bufferedReader.readLine()) != null) {
// Step 2: convert String into character-array
// using toCharArray() method
char[] chArray = line.toCharArray();
// Step 3: iterate through char[] array
for(char ch : chArray) {
// Step 4: leave spaces
if(ch != ' '){
// Step 4.1: convert all,
// char into upper case, before comparison
char upperChar= Character.toUpperCase(ch);
// Step 5: check
// whether Map contains same character
if(mapOfRepeatedChar
.containsKey(upperChar)) {
// Step 6: If contains,
// increase count value by 1
mapOfRepeatedChar.put(upperChar,
mapOfRepeatedChar.get(
upperChar) + 1);
}
else {
// Step 7: otherwise, make a new entry
mapOfRepeatedChar.put(upperChar, 1);
}
}
}
}
System.out.println("Before sorting : \n");
System.out.println("Char" + "\t" + "Count");
System.out.println("====" + "\t" + "=====");
// Step 8: get keySet() for iteration
Set<Character> character = mapOfRepeatedChar.keySet();
// Step 9: print word along with its count
for(Character ch : character) {
System.out.println(ch
+ "\t" + mapOfRepeatedChar.get(ch));
}
// Step 10: Sorting
// provide logic by invoking sortByCountValue();
Map<Character, Integer> wordLHMap = sortByCountValue(
mapOfRepeatedChar);
System.out.println("\n\nAfter sorting"
+ " in descending order of count : \n");
System.out.println("Char" + "\t" + "Count");
System.out.println("====" + "\t" + "=====");
// Step 11: Again print after sorting
for(Map.Entry<Character, Integer> entry :
wordLHMap.entrySet()){
System.out.println(entry.getKey()
+ "\t" + entry.getValue());
}
}
catch (FileNotFoundException fnfex) {
fnfex.printStackTrace();
}
catch (IOException ioex) {
ioex.printStackTrace();
}
}
/**
* this method sort acc. to count value
* @param mapOfRepeatedWord
* @return
*/
public static Map<Character, Integer> sortByCountValue(
Map<Character, Integer> mapOfRepeatedWord) {
// get entrySet from HashMap object
Set<Map.Entry<Character, Integer>> setOfWordEntries =
mapOfRepeatedWord.entrySet();
// convert HashMap to List of Map entries
List<Map.Entry<Character, Integer>> listOfwordEntry =
new ArrayList<Map.Entry<Character, Integer>>(
setOfWordEntries);
// sort list of entries using Collections.sort(ls, cmptr);
Collections.sort(listOfwordEntry,
new Comparator<Map.Entry<Character, Integer>>() {
@Override
public int compare(Entry<Character, Integer> es1,
Entry<Character, Integer> es2) {
return es2.getValue().compareTo(es1.getValue());
}
});
// store into LinkedHashMap for maintaining insertion
Map<Character, Integer> wordLHMap =
new LinkedHashMap<Character, Integer>();
// iterating list and storing in LinkedHahsMap
for(Map.Entry<Character, Integer> map : listOfwordEntry) {
wordLHMap.put(map.getKey(), map.getValue());
}
return wordLHMap;
}
}
Output:
Before sorting :
Char Count
==== =====
A 6
B 4
C 3
E 2
H 3
I 2
K 4
L 4
M 2
N 5
P 1
S 5
T 2
Y 1
After sorting in descending order of count :
Char Count
==== =====
A 6
N 5
S 5
B 4
K 4
L 4
C 3
H 3
E 2
I 2
M 2
T 2
P 1
Y 1
Note: Stop at Step 9, if there is no business requirements for sorting either way (ascending or descending)
Related Articles:
- Java 8 – Count and print number of lines and words in a text file
- Java 8 – Count and print number of repeated word occurrences in a text file
- Java 8 – Count and print number of repeated character occurrences in a String
- Java – Count and print number of words and lines in a text file
- Java – Count and print number of repeated word occurrences in a String
- Java – Count and print number of repeated character occurrences in a String
Hope, you found this article very helpful. If you any suggestion or want to contribute to improve this article, then share with us. We will include that code here.
Happy Coding !!
Happy Learning !!