Search code examples
javacollections

Sort map based on values in decreasing order


 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.


Solution

  • 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());
    }