Occurrence of character in Java

Prior Java8

package com.stackbyt;

import java.util.HashMap;
import java.util.Map;

public class CharOccurrence {
    private static void printCharOccurrence(String input){
        Map<Character,Integer> charMap = new HashMap<>();
        for(char ch : input.toCharArray()){
           if(ch == ' ') // ignore space character
               continue;
            if(charMap.containsKey(ch)){
                charMap.put(ch,charMap.get(ch)+1);
            }else{
                charMap.put(ch,1);
            }
        }
        System.out.println(charMap);
    }
    public static void main(String[] args) {
        printCharOccurrence("java programming ");
    }
}

Using Java8

public class CharOccurrence {
    public static void charOccurrenceUsingJava8(String input) {
        Map<Character, Long> collectMap = input.chars()
                .mapToObj(ch -> (char) ch)
                .filter(ch -> ch != ' ')
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        System.out.println(collectMap);
    }
    public static void main(String[] args) {
        charOccurrenceUsingJava8("java programming");
    }
}

Leave a Comment