Given a string, calculate the frequency of characters, output the array with the letter and frequency. (such as: for “abbcdc”, the output should be (a,1),(b,2),(c,2),(d,1))



import java.util.LinkedHashMap;
import java.util.Map;


public class StringUtils {

    public static void main(String[] args) {
        String str = "abbcdc";
        Map charFreqMap = new LinkedHashMap();
        char[] charArray = str.toCharArray();
        for (Character ch : charArray) {
            if (charFreqMap.get(ch) != null) {
                charFreqMap.put(ch, charFreqMap.get(ch) + 1);
            } else {
                charFreqMap.put(ch, 1);
            }
        }
        for (Map.Entry mapEntry : charFreqMap.entrySet()) {
            System.out.print("(" + mapEntry.getKey() + "," + mapEntry.getValue() + ")");
            System.out.print(",");
        }
    }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s