Java 8 Stream API: Counting Characters in a String

🟢 How to Count Characters in a String using Java 8 Stream API Input type: String = "Welocometoprogrammming" Output Type : Map<Character, Long> ✅ Code Example import java.util.*; import java.util.stream.*; import java.util.function.Function; public class Main { public static void main(String[] args) { String str = "Welocometoprogrammming"; Map<Character, Long> chCount = str.chars() .mapToObj(c -> (char) c) .collect(Collectors.groupingBy( Function.identity(), Collectors.counting() )); System.out.println(chCount); } } Output: {a=1, c=1, e=2, g=2, i=1, l=1, m=4, n=1, o=4, p=1, r=2, t=1, W=1} 🧠 Let’s Understand the Approach 🔹 Do we need a filter? ➡️ No, because we want to count all characters. 🔹 Do we need transformation? ➡️ No logical transformation, only type conversion. 🔹 Why chars()? ➡️ chars() converts the String into an IntStream of character ASCII values. 🔹 Why mapToObj()? ➡️ Because char is a primitive type, and Stream operations work on objects. So we convert each int to Character. 🔹 Why collect()? ➡️ Because the final result needs to be stored in Map<Character, Long>. ❓ What is Function.identity()? Function.identity() is a static method from java.util.function.Function. ✔️ It returns the same input as output ✔️ It is a replacement for this lambda: c -> c ✔️ Used when key and value are the same object Example: Collectors.groupingBy(Function.identity(), Collectors.counting()) Means: 👉 Group characters by themselves and count occurrences. #Java #Java8 #StreamAPI #Coding #InterviewPreparation #JavaStream #Multithreading

  • text

CountCharacters: String str = "Welocometoprogrammming"; Map<Character, Long> CountCharacters=str.chars().mapToObj(c->(char)c).collect(Collectors.groupingBy(Function.identity(),Collectors.counting())); System.out.print("CountCharacters "+CountCharacters);

To view or add a comment, sign in

Explore content categories