1

I want to enter some text, to separate the letters and then make a hashmap with keys-> unique letters of text and values -> number of repeated letters.How to sort values of Hashmap by descending order.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;

public class Menu {
    public static void main(String args[]){

        String text = null;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Please enter some text: ");
        try {
            text = br.readLine();

        } catch (IOException e) {
            e.printStackTrace();
        }

        HashMap<Character, Integer>  map = new HashMap();

        String UpperCase = text.toUpperCase();
        for (int i = 0;i < UpperCase.length(); i++){


            Character currentChar = UpperCase.charAt(i);

            if(map.get(currentChar) == null){
                map.put(currentChar, 1); 
            } else {
                map.put(currentChar, map.get(currentChar) + 1); 
            }

        }

        for (Character name: map.keySet()){

            String key = name.toString();
            String value = map.get(name).toString();  
            System.out.println(key + " " + value);  

            }
    }    

}
Supreme
  • 109
  • 7

1 Answers1

4

Transform the map into a List<Map.Entry<Character, Integer>>:

List<Map.Entry<Character, Integer>> entries = new ArrayList<>(map.entrySet());

then sort this list by entry value, using a Comparator<Map.Entry<Character, Integer>>.

Or, instead of storing an Integer as value of the map, store an instance of CharacterOccurence:

public class CharacterOccurrence {
    private char character;
    private int count;
    ...
}

Then create a list from the values of the map, and sort this list.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255