java - Sort a map on key and value -
i want sort map on key , value. first on key on value. example, should result;
1,2 1,3 2,1 2,2
anyone has suggestion on how achieve effectively? i've been seeing people using treemap sort keys, need values.
or ofcouse other method of sorting pairs on key , value welcome.
import java.util.sortedset; import java.util.treeset; public class sortmaponkeyandvalue { public static void main(string[] args) { sortedset<keyvaluepair> sortedset = new treeset<keyvaluepair>(); sortedset.add(new keyvaluepair(1, 2)); sortedset.add(new keyvaluepair(2, 2)); sortedset.add(new keyvaluepair(1, 3)); sortedset.add(new keyvaluepair(2, 1)); (keyvaluepair keyvaluepair : sortedset) { system.out.println(keyvaluepair.key+","+keyvaluepair.value); } } } class keyvaluepair implements comparable<keyvaluepair>{ int key, value; public keyvaluepair(int key, int value) { super(); this.key = key; this.value = value; } public int compareto(keyvaluepair o) { return key==o.key?value-o.value:key-o.key; } }
Comments
Post a Comment