Sort map by key and value

I want to sort the map by key and value. First by key, then by value. For example, it should be a result;

1,2 1,3 2,1 2,2

Anyone have a suggestion on how to do this effectively? I have seen people using TreeMap to sort keys, however I also need values.

Or you can use any other method of sorting pairs by key and value.

+4
source share
8 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; } } 
+5
source

What you are looking for is SortedSetMultimap , part of the Google Guava library. The implementation they include is called TreeMultimap :
http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/collect/TreeMultimap.html

If you are not familiar with this, Guava is a fantastic library with lots of great stuff that you think should be in standard Java libraries. I think that Java 8 will actually include some things from Guava (at least I thought it was a drift of this element: http://openjdk.java.net/jeps/108 ).

+3
source

It looks like you need a few types of cards, for example.

 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}} 
+1
source

This is not possible because the card cannot contain duplicate keys. A TreeMap always sorted by key value (assuming the key type is Comparable ).


But for this task, we usually take a map whose values ​​are lists:

 Map<Integer, List<Integer>> map = new TreeMap<Integer, List<Integer>>(); // add some values in random order List<Integer> list = new ArrayList<Integer>(); list.add(2); list.add(1); map.put(2,list); list = new ArrayList<Integer>(); list.add(2); list.add(1); map.put(1,list); // result for (Integer key:map.keySet()) { // map is already sorted List<Integer> value = map.get(key); Collections.sort(value); // list of values needs sorting for (Integer innerValue:value) { System.out.printf("%s : %s%n", key, innerValue); } } 
0
source

you cannot have such a card

  1->11 1->21 

key '1' is shared, so 21 will replace 11

0
source

If you are willing to take the risk, you can use a constructor that allows you to specify a comparator: http://download.oracle.com/javase/1.5.0/docs/api/java/util/TreeMap.html#TreeMap%28java .util.Comparator% 29

Having said that, what you want to do is ugly as black and illegal, because: * the order is not consistent with equals (), which is mandatory for SortedSet) * the order may change due to a change in the values ​​in the Map, and I don’t I know if its implementation allows it.

I think you need something else. Perhaps you would be better off creating an object with a key and value and correctly implement equals (), hashcode () and Comparable and use a SortedSet with it.


EDIT: I answered a general question (sort the map by key and value) without looking at your samples. As others have written, you cannot duplicate keys on a map.

0
source

Other answers indicate a problem with duplicate keys, but I assume that you have pairs that you want to sort, and the card bit was just an error. The cleanest solution I can think of is to create a custom Pair class that implements Comparator and compares both the key and the value of two pairs. Then you can use Collections.sort to sort.

0
source

The general idea is to convert the map to a list, sort the list, and put the sorted list back on the map.

Map ---> List ---> Sort ---> Map

Example

 import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; public class SortMyMap{ public static void main(String[] args) { System.out.println("Unsort Map......"); Map<String,String> unsortMap = new HashMap<String,String>(); unsortMap.put("1", "1"); unsortMap.put("2", "A"); unsortMap.put("3", "2"); Iterator iterator=unsortMap.entrySet().iterator(); for (Map.Entry entry : unsortMap.entrySet()) { System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue()); } System.out.println("Sorted Map......"); Map<String,String> sortedMap = sortByComparator(unsortMap); for (Map.Entry entry : sortedMap.entrySet()) { System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue()); } } private static Map sortByComparator(Map unsortMap) { List list = new LinkedList(unsortMap.entrySet()); //sort list based on comparator Collections.sort(list, new Comparator() { public int compare(Object o1, Object o2) { return ((Comparable) ((Map.Entry) (o1)).getValue()) .compareTo(((Map.Entry) (o2)).getValue()); } }); //put sorted list into map again Map sortedMap = new LinkedHashMap(); for (Iterator it = list.iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry)it.next(); sortedMap.put(entry.getKey(), entry.getValue()); } return sortedMap; } } 
0
source

All Articles