How to sort java sort map by values with the compare method already in class? -
i want sort map values. compare method in class.
public class parser implements comparator<string> { private map<string, integer> frequencies; public parser() { frequencies = new hashmap<string, integer>(); } public int getcount(string word) { integer c = frequencies.get(word); if (c == null) { homecoming 0; } else { homecoming c.intvalue(); } } public int compare(string o1, string o2) { int count1 = getcount(o1); int count2 = getcount(o2); homecoming count1 < count2 ? -1 : count1 > count2 ? 1 : 0; } public list<string> getwordsinorderoffrequency(){ treemap<string,integer> sorted_map = new treemap<string,integer>(); sorted_map.putall(frequencies); arraylist<string> result = new arraylist<string>(sorted_map.keyset()); homecoming result; } } here question in getwordsinorderoffrequenct() method. want sort keyset values after compared.
here code snippet can observe how achieved that
public class wordfrequency { public static string sentence = "one 3 2 2 3 3 4 4 four"; public static map<string, integer> map; public static void main(string[] args) { map = new hashmap<>(); string[] words = sentence.split("\\s"); (string word : words) { integer count = map.get(word); if (count == null) { count = 1; } else { ++count; } map.put(word, count); } comparator<string> mycomparator = new comparator<string>() { @override public int compare(string s1, string s2) { if (map.get(s1) < map.get(s2)) { homecoming -1; } else if (map.get(s1) > map.get(s2)) { homecoming 1; } else { homecoming s1.compareto(s2); } } }; sortedmap<string, integer> sortedmap = new treemap<string, integer>(mycomparator); system.out.println("before sorting: " + map); sortedmap.putall(map); system.out.println("after sorting based on value:" + sortedmap); } } java
No comments:
Post a Comment