java - Sort a list by frequency of strings in it -
this question has answer here:
list is
list<string> list = new arraylist<string>(); list.add("apple"); list.add("ball"); list.add("apple"); list.add("cat"); list.add("ball");
now have sort list frequency of apple, ball, cat
i have output as:
apple ball cat
first, count occurrence of string , sort using map
list<string> list = new arraylist<string>(); list.add("apple"); list.add("ball"); list.add("apple"); list.add("cat"); list.add("ball"); map<string, integer> map = new hashmap<string, integer>(); (string s : list) { if (map.containskey(s)) { map.put(s, map.get(s) + 1); } else { map.put(s, 1); } } valuecomparator<string, integer> comparator = new valuecomparator<string, integer> (map); map<string, integer> sortedmap = new treemap<string, integer> (comparator); sortedmap.putall(map); list<string> sortedlist = new arraylist<string> (sortedmap.keyset()); system.out.println(sortedmap); system.out.println(sortedlist); } static class valuecomparator<k, v extends comparable<v>> implements comparator<k> { map<k, v> map; public valuecomparator(map<k, v> base) { this.map = base; } @override public int compare(k o1, k o2) { return map.get(o2).compareto(map.get(o1)); } }
Comments
Post a Comment