0
 Map<Character, Integer> map = new HashMap();
        for(char c : ch) {
            if(map.get(c) == null) {
                map.put(c, 1);
            } else {
                map.put(c, map.get(c)+1);
            }
        }
        for(Map.Entry entry : map.entrySet()) {
            System.out.println("Key is  "+ entry.getKey() + "  Value is  " + entry.getValue());
        }

I have a String str = "PriyankaTaneja"

I want to count the frequency of characters in the String using map and i want to sort the map in decreasing order of values, that means the character repeating the max number of times should be the first to print.

priyanka
  • 422
  • 2
  • 7
  • 19
  • Does this answer your question? [Sort ArrayList of custom Objects by property](https://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property) – Anonymous Atom Jul 03 '23 at 19:49

1 Answers1

1

To sort a map by values in descending order, you can use the Java stream API and the Comparator interface. For example:

Map<Character, Integer> map = new HashMap<>();
for(char c : ch) {
  if(map.get(c) == null) {
      map.put(c, 1);
  } else {
    map.put(c, map.get(c)+1);
  }
}

Map<Character, Integer> sortedMap = map.entrySet()
  .stream()
  .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
  .collect(Collectors.toMap(
    Map.Entry::getKey,
    Map.Entry::getValue, 
    (e1, e2) -> e1,
    LinkedHashMap::new
  ));

for(Map.Entry entry : sortedMap.entrySet()) {
  System.out.println("Key is  "+ entry.getKey() + "  Value is  " + entry.getValue());
}
Pluto
  • 4,177
  • 1
  • 3
  • 25