Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a map on key and value

Tags:

java

sorting

map

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.

like image 733
ferdyh Avatar asked Dec 28 '22 18:12

ferdyh


2 Answers

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;
    }
}
like image 75
hd42 Avatar answered Jan 11 '23 17:01

hd42


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).

like image 39
Joshua Humphries Avatar answered Jan 11 '23 17:01

Joshua Humphries