Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
501 views
in Technique[技术] by (71.8m points)

java - How to sort a character by number of occurrences in a String using a Map?

I wrote code that counts frequency of every character in a given string and displays it:

Map<Character, Integer> occurrences = new HashMap<>();
char[] chars = str2.toCharArray();
for (char character : chars) {
    Integer integer = occurrences.get(character);
    occurrences.put(character, integer);
    if (integer == null) {
        occurrences.put(character, 1);
    } else {
        occurrences.put(character, integer + 1);
    }
}
System.out.println(occurrences);

Now I want to modify my code, so it shows the characters ordered by their frequency. Starting with the character, that is most frequently repeated, then second most frequently, then third and so on.

For example the string Java should be displayed as character-frequency in following order: a=2, j=1, v=1.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Consider using a TreeMap ( https://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html )

TreeMap is a map implementation that keeps its entries sorted according to the natural ordering of its keys.

You can refer to the below code for reference.

import java.util.Map;
import java.util.TreeMap; 

class Test { 
    static void characterCount(String inputString) 
    { 
        TreeMap<Character, Integer> charCountMap = new TreeMap<Character, Integer>(); 
        char[] strArray = inputString.toCharArray(); 
        for (char c : strArray) { 
            if (charCountMap.containsKey(c)) { 
                charCountMap.put(c, charCountMap.get(c) + 1); 
            } 
            else { 
                charCountMap.put(c, 1); 
            } 
        } 
        for (Map.Entry entry : charCountMap.entrySet()) { 
            System.out.println(entry.getKey() + "=" + entry.getValue()); 
        } 
    } 

    public static void main(String[] args) 
    { 
        String str = "welcometostackoverflow"; 
        characterCount(str); 
    } 
} 

Output :

a=1
c=2
e=3
f=1
k=1
l=2
m=1
o=4
r=1
s=1
t=2
v=1
w=2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...