Problem:
Using Java 8 Streams, how do you count the number of occurrences of each character in a given string (ignoring spaces)?
✅ Example:
import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class CharacterCount {
public static void main(String[] args) {
String input = "Hello Everyone";
Map<String, Long> charToCount = Arrays.stream(input.replaceAll("\\s+", "").split(""))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
charToCount.forEach((character, count) ->
System.out.println("Character: " + character + ", Count: " + count));
}
}
✅ Example Output:
Character: H, Count: 1
Character: e, Count: 4
Character: l, Count: 2
Character: o, Count: 2
Character: v, Count: 1
Character: r, Count: 1
Character: y, Count: 1
Character: n, Count: 1
✅ Explanation:
- Normalization Step:
input.replaceAll("\\s+", "")
- Removes all spaces from the input string
"Hello Everyone"
→"HelloEveryone"
.
- Removes all spaces from the input string
- Splitting into Characters:
.split("")
- Splits the string into individual characters:
["H", "e", "l", "l", "o", "E", "v", "e", "r", "y", "o", "n", "e"]
.
- Splits the string into individual characters:
- Stream Processing:
Arrays.stream(...)
- Converts the array of characters into a stream.
- Grouping and Counting:
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
- Groups characters by themselves and counts the number of occurrences.
- Printing the Result:
charToCount.forEach((character, count) -> System.out.println(...));