I want to sort a Map on key and value. First on key then on value. For example, this should be the result;
1,2
1,3
2,1
2,2
Anyone has a suggestion on how to achieve this effectively? I've been seeing people using a TreeMap to sort keys, however i also need values.
Or ofcouse any other method of sorting pairs on key and value is 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));
for (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;
}
}
What you are looking for a is SortedSetMultimap
, part of Google's Guava library. The implementation they include is named TreeMultimap
:
http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/collect/TreeMultimap.html
If you're not familiar with it, Guava is a fantastic library with lots of great stuff that you sometimes think should be in the standard Java libraries. I think Java 8, actually, will include some stuff from Guava (at least that seemed to me to be the drift of this item: http://openjdk.java.net/jeps/108).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With