A treemap is a red-black tree that is a balanced binary search tree . In other words, the tree is already sorted (more precisely, ordered by the rules of the binary search tree) with its balanced height, so tree operations have complexity O (log n). However, I think you want to print all the keys in sorted order. This is as simple as implementing the traversal order in the treemap, or you can use the keySet () method to get the Set and iterate over the values.
eg. workaround
void inorderTraversal( Node root ){ if( root == null ) return; inorderTraversal( root.getLeft() ); root.printValue(); inorderTraversal( root.getRight() ); }
EDIT
OK, I'm 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]
Thus, 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 note that the presence of "variable keys" and variable values ββare completely different.
Dhruv gairola
source share