Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting treemap based on key, where key is variable

Tags:

java

treemap

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.

like image 778
sachin Avatar asked Aug 03 '11 11:08

sachin


1 Answers

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.

like image 151
Dhruv Gairola Avatar answered Oct 11 '22 21:10

Dhruv Gairola