Sort a map on key and value

11,841

Solution 1

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;
    }
}

Solution 2

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

Solution 3

Sounds like you want a multi map of some type e.g.

SortedMap<Key, SortedSet<Value>> map = new TreeMap<Key, SortedSet<Value>>();

map.put(1, new TreeSet<Integer>(Arrays.asList(1, 2)));
map.put(2, new TreeSet<Integer>(Arrays.asList(2, 1)));

System.out.println(map);

prints

{ 1 = {1, 2}, 2 = {1, 2}}
Share:
11,841
ferdyh
Author by

ferdyh

Updated on June 13, 2022

Comments

  • ferdyh
    ferdyh almost 2 years

    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.

  • ferdyh
    ferdyh almost 13 years
    Blimmey, thats fancy :) Why didnt i think of that.. :)
  • Amessihel
    Amessihel over 5 years
    You're comparing on value, that's not what he wanted I guess.
  • Spandan
    Spandan about 5 years
    Ya you are right... My post is to sort either by key or Value... :)
  • Spandan
    Spandan about 5 years
    I have posted other question for my answer :- stackoverflow.com/questions/54909215/…