如何按键订购地图值?

时间:2015-03-30 19:45:51

标签: java dictionary enums maps guava

我有以下情况,我尝试按键排序地图值。在键顺序之后,第一个值必须是按顺序排列的值。

import java.util.Comparator;
import java.util.Map;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;

public class MyEnumKeySortTest {


    enum Key{
        key1, key2
    }

    enum Door{
        door1, door2 
    }


     public static void main(String[] args) {
        Map<Key, Door> test = ImmutableMap.<Key, Door> of(Key.key1, Door.door1, Key.key2, Door.door2);

        printValues(test);
        Comparator<Key> comparator =  Ordering.explicit(Key.key1);
        /*
         *  should print
         *  
         *  door1
         *  door2
         */

        test = Maps.newTreeMap(comparator);
        printValues(test);

        Comparator<Key> comparator2 =  Ordering.explicit(Key.key2);
        /*
         *  should print
         *  
         *  door2
         *  door1
         */

        test = Maps.newTreeMap(comparator2);
        printValues(test);

     }


    private static void printValues(Map<Key, Door> test) {
        System.out.println("==========================================================");
        for(Door r : test.values()){
            System.out.println(r.name());
        }
    }

}

1 个答案:

答案 0 :(得分:0)

Map.Entry放入列表中,并使用对值进行排序的比较器对其进行排序 -

List list = new ArrayList(map.entrySet());
Collections.sort(list, new Comparator() {

  @Override
  public int compare(Entry e1, Entry e2) {
    return e1.getKey().compareTo(e2.getKey());
  }

});

或者可以使用SortedMap之类的一些实现 - TreeMap。在这种情况下,所有密钥可能必须实现Comparable