How to Count Characters of Each String in Java 8 Using Stream API

This example count characters of each string of an array using Java 8 Stream API .

Code Explanation (Step-by-Step)

  • First, we create an array of strings: “java”, “tech”, “note”, and “com”.
  • Then we use Stream.of() to convert the array into a stream.
  • The mapToInt() method converts each string into its length by using length().
  • Finally, forEach() prints the length of each string.
				
					import java.util.stream.IntStream;
import java.util.stream.Stream;

public class CountChar {
	public static void main(String[] args) {
		String[] words = { "java", "tech", "note", "com" };
		
		Stream<String> stream = Stream.of(words);
		IntStream lengths = stream.mapToInt(word -> word.length());
		
		lengths.forEach(System.out::println);
	}
}
				
			
Output :- 
4
4
3

Count Characters in Java 8 Using Stream API :

				
					import java.util.stream.Stream;

public class CountChar {
	public static void main(String[] args) {

		String[] words = { "java", "tech", "note", "Hibernate" };

		Stream.of(words).forEach(word -> System.out.println(word + " : " +
		                                  word.length()));
	}
}
				
			

Output :-
java : 4
tech : 4
note : 4
Hibernate : 9