java - Count of chars in char array in descending order -


there char array shown below. need print count of each character in descending order of count.

char arr[] = {'a', 'b', 'e', 'a', 'c', 'd', 'e', 'a', 'c', 'e', 'b', 'a', 'a', 'b','e','e'}; 

looking efficient solution problem. have tried hashmap, arraylist combinations. there way to hashmap alone, without using arraylist(or other list implementations).

try again using treemap override compare. this:

public static void main(string[] args) {     char[] arr = {'a', 'b', 'e', 'a', 'c', 'd', 'e', 'a', 'c', 'e', 'b', 'a', 'a', 'b','e','e'};     map<character, integer> map = new hashmap<>();     (char c: arr){         if (!map.containskey(c)){             map.put(c, 1);         }else{             map.put(c, map.get(c)+1);         }     }     valuecomparator vc = new valuecomparator(map);     map<character, integer> sortedmap = new treemap<character, integer>(vc);     sortedmap.putall(map);     system.out.println(sortedmap); }  public class valuecomparator implements comparator<character>   {      map<character, integer> map;      public valuecomparator(map<character, integer> map){         this.map = map;     }       @override     public int compare(character a, character b) {         if (map.get(a) >= map.get(b)) {             return -1;         } else {             return 1;         } // returning 0 merge keys      }  } 

output:

{a=5, e=5, b=3, c=2, d=1} 

hope helps!


Comments

Popular posts from this blog

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

html - Outlook 2010 Anchor (url/address/link) -

android - How to create dynamically Fragment pager adapter -