开发者

sorting treemap based on key, where key is variable

I want to sort the tree map based on the key where key is a variable,so sorting should be based on variable val开发者_StackOverflowue, 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.


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜