Home > Back-end >  Find the max and min frequency of characters in a string
Find the max and min frequency of characters in a string

Time:11-22

    public void charFrequency(){
        int maximumCount = 0;
        int minimumCount = 0;

        for (int i = 0; i <str.length() ; i  ) {
            char c = str.charAt(i);
            if(numCount.containsKey(c)){
                int count = numCount.get(c);
                count  ;
            if(maximumCount<count)                  
                maximumCount  ;                     
                numCount.put(c, count);             
            }else{
                numCount.put(c, 1);
                minimumCount = 1;
            }
        }

        
        System.out.println("Characters with most frequency in String");
        for(char maxKey: numCount.keySet()){
            if(numCount.get(maxKey) == maximumCount){
                System.out.println("Character: "   maxKey   "\t Have frequency of: "    maximumCount);
            }
        }

        
        System.out.println("Characters with the lowest frequency in String");
        for(char minKey: numCount.keySet()){
            if(numCount.get(minKey) == minimumCount){
                System.out.println("Character: "   minKey   "\t Have frequency of: "    minimumCount);
            }
        }
    }

I need to find the frequency of all the characters, for example if i had the string "HELLO WORLD!" the characters "L" AND " O" are the 2 characters with most frequency..

but i can't understand what to do to.. for example i want to print that:

Character: L: have frequency of 3

Character: O: have frequency of 2

Character: H E R D have frequency of 1 1 1 1

CodePudding user response:

This should do the trick. You can also use the map to check the frequency of all other characters. Also if theres other characters which should not be counted, you can just add this below and it should be removed. map.remove('character')

Instead of the map.remove('character'), you could also replace the counting loop with this where c != ' ' does the trick. You can add as many as you want there (c != ' ' && c != 'a')

   Map<Character, Integer> map = new HashMap<>();
    for (int i = 0; i < str.length(); i  ) {
        char c = str.charAt(i);
        if(c != ' '){
            if (map.containsKey(c)) {
                map.put(c, map.get(c)   1);
            } else {
                map.put(c, 1);
            }
        }
    }

Solution:

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

public class test {
    public static void main(String[] args) {
        charFrequency("Hello World");
    }

    public static void charFrequency(String str){
        //count the characters
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < str.length(); i  ) {
            char c = str.charAt(i);
            if (map.containsKey(c)) {
                map.put(c, map.get(c)   1);
            } else {
                map.put(c, 1);
            }
        }

        //remove "space" characters from map
        map.remove(' ');

        //print out the most frequent character
        int max = 0;
        char maxChar = ' ';
        for (Map.Entry<Character, Integer> entry : map.entrySet()) {
            if (entry.getValue() > max) {
                max = entry.getValue();
                maxChar = entry.getKey();
            }
        }
        System.out.println("The most frequent character is "   maxChar   " and it appears "   max   " times");

        //print out the lowest frequent character
        int min = Integer.MAX_VALUE;
        char minChar = ' ';
        for (Map.Entry<Character, Integer> entry : map.entrySet()) {
            if (entry.getValue() < min) {
                min = entry.getValue();
                minChar = entry.getKey();
            }
        }
        System.out.println("The least frequent character is "   minChar   " and it appears "   min   " times");
    }
}

CodePudding user response:

Here is a simple solution using Stream API:

TreeMap<Long, List<String>> map = str.chars()
        .boxed()
        .collect(Collectors.collectingAndThen(
                // group by the character frequency to Map<String, Long>
                Collectors.groupingBy(
                        // group by characters
                        ch -> ((char) ch.intValue()   ""),
                        // and let the value be their frequency
                        Collectors.counting()),
                // invert the map and group same frequencies into the list
                intermediateMap -> intermediateMap.entrySet().stream()
                        .collect(
                                // reverse order sorted map implementation
                                () -> new TreeMap<>(Comparator.reverseOrder()),
                                // fill in TreeMap<Long, List<String>>
                                (m, entry) -> m.computeIfAbsent(
                                                entry.getValue(), 
                                                l -> new ArrayList<>())
                                        .add(entry.getKey()),
                                // combiner
                                TreeMap::putAll)));

map.forEach((key, value) -> {
    System.out.printf("Character(s): [%s] have frequency of %s%n", 
        String.join(" ", value), key);
});

Output:

Character: [L] have frequency of 3
Character: [O] have frequency of 2
Character: [  ! R D E W H] have frequency of 1
  • Related