Write Java program that generates the occurrence of each character in a given string:
1 ) package details;
import java.util.HashMap;
public class occurenceOfCharacters {
public static void main(String[] args) {
String s = "hello";
char[] chars = s.toCharArray();
HashMap<Character, Integer> mapData = new HashMap<>();
for(int i=0;i<s.length();i++) {
if(mapData.containsKey(s.charAt(i))) {
mapData.put(chars[i], mapData.get(chars[i])+1);
}
else {
mapData.put(chars[i], 1);
}
}
mapData.forEach((k, v) -> System.out.println( k + " " + v));
}
}
Output : e 1
h 1
l 2
o 1
Explanation:
- The program uses a
HashMap
to store the characters as keys and their respective counts as values. - It loops through each character in the string and updates the map accordingly.
- Finally, it prints out the occurrences of each character.
2 ) import java.util.HashMap;
import java.util.Map;
public class CharacterOccurrence {
public static void main(String[] args) {
String inputString = "programming"; // You can change the string here
countCharacterOccurrences(inputString);
}
public static void countCharacterOccurrences(String str) {
// Creating a map to store the frequency of each character
Map<Character, Integer> charCountMap = new HashMap<>();
// Loop through each character of the string
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
// Directly use getOrDefault to handle count updates
charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1);
}
// Display the result
System.out.println("Character occurrences in the string:");
for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
Key Improvements:
getOrDefault(c, 0)
: This allows us to retrieve the current count for a character or return0
if it doesn't exist. We then increment this value directly, eliminating the need for anif-else
check.- Single pass through the string: We're directly iterating over the string's characters using
charAt(i)
, which avoids converting the string to a character array, making it more memory efficient.
Output :
Character occurrences in the string:
p: 1
a: 3
r: 2
v: 1
g: 2
i: 1
j: 1
m: 2
n: 1
o: 1
3) public static void countCharacterOccurrences(String str) {
// Using Java Streams to count character occurrences
Map<Character, Long> charCountMap = str.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
// Display the result
charCountMap.forEach((key, value) -> System.out.println(key + ": " + value));
}
Explanation:
str.chars()
converts the string into anIntStream
of character values..mapToObj(c -> (char) c)
converts the primitiveint
values back toCharacter
objects.Collectors.groupingBy(Function.identity(), Collectors.counting())
groups characters and counts their occurrences
Ouptut:
p: 1
a: 3
r: 2
v: 1
g: 2
i: 1
j: 1
m: 2
n: 1
o: 1
No comments:
Post a Comment