count of each character in a String using Java 8
Categories: Java 8(JDK1.8) Java Java Examples
package r4r.co.in;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CountEachCharacterInGivenString {
public static void main(String[] args) {
// count of each character in a String using Java 8
String str = "I am Rajesh Kumar";
//
Map<Object, Long> mapUsingHashMap = Stream.of(str.split("")).filter(f -> !f.isBlank()).map(s -> s.toLowerCase())
.collect(Collectors.groupingBy(s -> s, HashMap::new, Collectors.counting()));
System.out.println(mapUsingHashMap);
Map<Object, Long> mapUsingLinkedHashMap = Stream.of(str.split("")).filter(f -> !f.isBlank())
.map(s -> s.toLowerCase())
.collect(Collectors.groupingBy(s -> s, LinkedHashMap::new, Collectors.counting()));
System.out.println(mapUsingLinkedHashMap);
Map<Object, Long> mapUsingFuntionIdentity = Stream.of(str.split("")).filter(f -> !f.isBlank())
.map(s -> s.toLowerCase()).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.print(mapUsingFuntionIdentity);
}
}
OutPut
{a=3, r=2, s=1, u=1, e=1, h=1, i=1, j=1, k=1, m=2}
{i=1, a=3, m=2, r=2, j=1, e=1, s=1, h=1, k=1, u=1}
{a=3, r=2, s=1, u=1, e=1, h=1, i=1, j=1, k=1, m=2}