11

I want to sort the tree map based on the key where key is a variable,so sorting should be based on variable value, How can we achieve this? I want use in built sort method rathar implementing it through code, any reply with example is of great help.

sachin
  • 115
  • 1
  • 1
  • 8
  • what would that key be? any examples? – asgs Aug 03 '11 at 11:45
  • thanks for the reply, here key is variable, `k=3, l=2 ,m=1` so in this case I want to sort key `m – sachin Aug 03 '11 at 11:57
  • Do you mean you want to sort by values, rather than sort by keys? – Dhruv Gairola Aug 03 '11 at 12:07
  • @Dhruv consider this case. I want to implement key as a variable. like a=1,b=3,c=2 it should be sorted according to it's values. eg:when you map (a,"one") (b,"three")(c,"two"). after sorting print statment should print one,two,three and not one,three,two – sachin Aug 03 '11 at 12:12

3 Answers3

24

TreeMap (which implements SortedMap) stores automatically the keys in the correct order:

Map<Integer, String> map = new TreeMap<Integer, String>();
map.put(1, "one");
map.put(3, "three");
map.put(2, "two"); 
// prints one two three   
for(Integer key : map.keySet()) {
    System.out.println(map.get(key));
}

As Key-Type (in that case Integer) you can use any class which implements Comparable (or you can provide a Comparator when creating the TreeMap)

Edit: Okay, here is a suggestion how to re-map your map.

Map<Integer, String> oldMap; // get oldMap from somewhere
// Prepare remapping
Map<Integer, String> newMap = new TreeMap<Integer, String>();
Map<Integer, Integer> keyMap = new HashMap<Integer, Integer>();
// Store a new key for each old key
keyMap.put(oldKey, newKey);
// fill the newMap
for(Integer oldKey : keyMap.keySet()) {
    newMap.put(keyMap.get(oldKey), oldMap.get(oldKey));
}
oldMap = newMap; // if needed
Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243
pmnt
  • 379
  • 1
  • 6
  • @ pmnt thanks for the replay I want to implement key as a variable. like a=1,b=3,c=2 it should be sorted according to it's values. eg: (a,"one") (b,"three")(c,"two"). if you sort it according to your print statment it should print one,two,three and not one,three,two – sachin Aug 03 '11 at 12:02
  • @sachin: sry, but the Key Class **should** be immutable (unable to be changed after creation).This has 2 reasons: 1) If you change the value of a key, it can not be guaranteed that the key is unique after the change. 2) The values in the Map are sorted in correct order when you add the value. So when you want to change the order of the values in the Map, you have to recreate it – pmnt Aug 03 '11 at 12:24
  • @pmnt actually, what sachin wants is to sort by values. he expressed himself wrongly. – Dhruv Gairola Aug 03 '11 at 12:41
  • I will explain the case clearly, consider this `int a=1; int b=3; int c=2; put these varaible as key in a map put(a,x),put(b,y),put(c,z) when you sort the map and print it output should be x fallowed by z fallowed by y. – sachin Aug 03 '11 at 12:47
  • sry, I don't get your problem. Nothing hinders you from adding values via `map.put(a,x)`. It's only important to understand that changing `a` AFTER the insertion into the map WILL NOT change the sorting order in the map. And there is nothing you can do about it - except remapping your new key/value pairs. – pmnt Aug 03 '11 at 13:07
2

A treemap is a Red-black tree, which is a balanced binary search tree. In other words, the tree is already sorted (or rather, arranged as per the binary search tree rules) with its height balanced so that tree operations have a O(lg n) complexity. However, I think what you want is to print all the keys in sorted order. This is as simple as implementing an inorder traversal on the treemap, or you could use the keySet() method to get a Set and iterate over the values.

e.g. of inorder traversal

void inorderTraversal( Node root ){
    if( root == null ) return;
    inorderTraversal( root.getLeft() );
    root.printValue();
    inorderTraversal( root.getRight() );
}

EDIT:

Okay, I'm pretty sure this is what you want. You want to sort by values:

        Map<String, Integer> map = new TreeMap<String, Integer>();
        map.put("one", 8);
        map.put("two", 10);
        map.put("three", 9);
        map.put("hundred", 1);
        System.out.println(map.values());

Output:

[1, 8, 9, 10]

So this works even for sorting string values:

    Map<Integer, String> map = new TreeMap<Integer, String>();
        map.put(8, "one");
        map.put(10, "two");
        map.put(9, "three");
        map.put(1, "hundred");
        System.out.println(map.values());

Output:

[hundred, one, three, two]

Also, sachin take note that having "variable keys" and variable values are completely different things.

Dhruv Gairola
  • 9,102
  • 5
  • 39
  • 43
  • thanks for the reply, here key is variable, `k=3, l=2 ,m=1` so in this case I want to sort key `m – sachin Aug 03 '11 at 11:52
  • basically key should be variable, sorting should be w.r.t value in varaible not on valuve mapped to key there is difference in these two. – sachin Aug 03 '11 at 12:44
  • @sachin if the key is a variable, then what will happen to its associated value when the key changes? – Dhruv Gairola Aug 03 '11 at 13:13
  • I dont think I can implement what i thoough as key is immutable it should be unique, so I have to look for the other slution. My require ment was I want sort the priority of a schemes and each scheme is associated with one mutual exclusive flag so when I sort the priority respective mutual exclusive flag should be in same index of array . can you point me to some solution ?? – sachin Aug 03 '11 at 13:29
0

TreeMap implements the SortedMap interface and is sorted by its key without you having to do anything:

The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • thanks for the reply, here key is variable, `k=3, l=2 ,m=1` so in this case I want to sort key `m – sachin Aug 03 '11 at 11:50