sorting treemap based on key, where key is variable

有些话、适合烂在心里 提交于 2019-12-05 03:36:23
pmnt

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

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.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!