Key based treemap sort, where key is a variable

I want to sort a tree map based on a key, where the key is a variable, so sorting should be based on the value of the variable. How can we achieve this? I want to use rathar's built-in sorting method that implements it using code, any answer with an example is of great help.

+7
source share
3 answers

TreeMap (which implements SortedMap ) automatically saves 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 a type key (in this case, Integer ) you can use any class that implements Comparable (or you can provide a Comparator when creating a TreeMap )

Edit: Ok, here is a suggestion on how to reconfigure the 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 
+15
source

TreeMap implements the SortedMap interface and is sorted by its key without doing anything:

The map is sorted according to the natural order of its keys or Comparator , provided the map is created, depending on the constructor.

0
source

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.

0
source

All Articles