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
171 views
in Technique[技术] by (71.8m points)

How to sort a character by number of occurrences in a String using map collection in java?

I wrote a code that counts every character in a given string and displays it. Now I want to modify my code, so it shows first character, that is mostly repeated, then second, third.
For example, "Java".
Result should be : a=2, j=1, v=1.

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 );
question from:https://stackoverflow.com/questions/65661145/how-to-sort-a-character-by-number-of-occurrences-in-a-string-using-map-collectio

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

1 Reply

0 votes
by (71.8m points)

If you use TreeMap it will keep your day sorted by Key.

You can read more about it here. There is also a constructor with your own Comparator if you need your way of sorting. https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html


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

...