Java Program to Find Frequency of each Character in a String - 5 Ways
In this section, we will show you five different ways to find frequency of each Character in a given String in Java.
1. Using For loop and Map
2. Using Enhanced for loop and Map
3. Using Java 9 chars() method
4. Using Java 8 Streams
5. Using Google Guava MultiSet
Example 1. Using For loop and Map
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
String str = "hello java hello java";
Map<Character,Integer> occurrences = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (occurrences.containsKey(c)) {
int count = occurrences.get(c);
occurrences.put(c, ++count);
} else {
occurrences.put(c, 1);
}
}
System.out.println(occurrences);
}
}
Here we iterate through string chars. Check whether map contains specific key. If map contains specific key get the value(count) and put the key and value(++count) inside HashMap. HashMap don't allow for duplicate keys. The second value should just replace the previous value.
Note, this example will count all of the characters including whitespace.
Example 2. Using Enhanced for loop and Map
import java.util.LinkedHashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
String str = "hello java hello java";
Map<Character, Integer> occurrences = new LinkedHashMap<>();
for (Character ch : str.toCharArray()) {
Integer count = occurrences.get(ch);
occurrences.put(ch, count == null ? 1 : ++count);
}
System.out.println(occurrences);
}
}
Here we iterate through string array. Get the count (value). Then put it to the Map, if count(value) is 'null' we put value as 1, if count(value) is 'not null' put value as count+1. The second value should just replace the previous value. It will not allow duplicate keys.
Note, this example will count all of the characters including whitespace.
Example 3. Using Java 9 chars() method
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
String str = "hello java hello java";
Map<Character, Long> collect =
str.chars().mapToObj(i -> (char) i)
.collect(Collectors.
groupingBy(c -> c, Collectors.counting()));
System.out.println(collect);
}
}
chars() returns an IntStream that consists of the code point values of the characters in the given string. This method was integrated to the String class in Java 9.
mapToObj() is an intermediate operation, it is a method of IntStream interface is used to return an object-valued stream.
Java Stream collect() performs a mutable reduction operation on the elements of the stream. This is a terminal operation.
The groupingBy() method of Collectors class in Java are used for grouping objects by some property and storing results in a Map instance. In order to use it, we always need to specify a property by which the grouping would be performed.
Collectors counting() method is used to count the number of elements passed in the stream as the parameter.
Note, this example will count all of the characters including whitespace.
Example 4. Using Java 8 Streams
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
String str = "hello java hello java";
Map<Character , Long> collect =
Arrays.stream(str.split("")).map(o ->o.charAt(0))
.collect(Collectors.groupingBy(c -> c , Collectors.counting()));
System.out.println(collect);
}
}
stream() method accepts a mandatory parameter array which is the array of whose elements are to be converted into a sequential stream and returns a Sequential Stream from the array passed as the parameter.
split() method is used to split the String.
Using map() method we are converting Stream<String> to Stream<Character>.
Java Stream collect() performs a mutable reduction operation on the elements of the stream. This is a terminal operation.
The groupingBy() method of Collectors class in Java are used for grouping objects by some property and storing results in a Map instance. In order to use it, we always need to specify a property by which the grouping would be performed.
Collectors counting() method is used to count the number of elements passed in the stream as the parameter.
Note, this example will count all of the characters including whitespace.
Example 5. Using Google Guava MultiSet
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
public class Main {
public static void main(String[] args) {
String str = "hello java hello java";
char[] chars = str.toCharArray();
Multiset<Character> frequencies = HashMultiset.create();
for (Character character : chars) {
frequencies.add(character);
}
for (Character character : frequencies.elementSet()) {
System.out.println(character + " =>" + frequencies.count(character) );
}
}
}
A Multiset is an collection that is kindred to Set, but it may have duplicate elements. The duplicate elements are fortified by maintaining a count of the total number of times an element appears in the collection.
More Interesting topics,