-->

Java的TreeMap的比较(Java TreeMap Comparator)

2019-06-18 14:02发布

我需要一个TreeMap的比较器。 我应该在构造函数中我TreeMap的匿名写的吗? 我还能怎么写我的比较。 目前,Java不喜欢我的代码(我可以做到这一点匿名?):

SortedMap<String, Double> myMap = 
    new TreeMap<String, Double>(new Comparator<Entry<String, Double>>()
    {
        public int compare(Entry<String, Double> o1, Entry<String, Double> o2)
        {
            return o1.getValue().compareTo(o2.getValue());
        } 
    });
  1. 我可以做上述匿名?
  2. 我还能怎么做呢?
  3. 我想用价值的关键不是排序MYMAP

Answer 1:

无法排序TreeMap的价值观。

红黑树基于NavigableMap实现。 该地图是根据其键的自然顺序进行排序,或者通过比较创建映射时提供的,这取决于使用的构造,您将需要提供comparatorComparator<? super K> Comparator<? super K>让你比较应该比较上的按键。

为了提供某种价值观,你需要的SortedSet 。 使用

SortedSet<Map.Entry<String, Double>> sortedset = new TreeSet<Map.Entry<String, Double>>(
            new Comparator<Map.Entry<String, Double>>() {
                @Override
                public int compare(Map.Entry<String, Double> e1,
                        Map.Entry<String, Double> e2) {
                    return e1.getValue().compareTo(e2.getValue());
                }
            });

  sortedset.addAll(myMap.entrySet());

给你举个例子

    SortedMap<String, Double> myMap = new TreeMap<String, Double>();
    myMap.put("a", 10.0);
    myMap.put("b", 9.0);
    myMap.put("c", 11.0);
    myMap.put("d", 2.0);
    sortedset.addAll(myMap.entrySet());
    System.out.println(sortedset);

输出:

  [d=2.0, b=9.0, a=10.0, c=11.0]


Answer 2:

比较应该只为关键,不是针对整个项目。 它排序基于密钥的条目。

你应该如下改变它的东西

SortedMap<String, Double> myMap = 
    new TreeMap<String, Double>(new Comparator<String>()
    {
        public int compare(String o1, String o2)
        {
            return o1.compareTo(o2);
        } 
});

更新

你可以做一些事情如下(创建在地图条目列表和值列表进行排序的基础,但要注意这不会对地图本身进行排序) -

List<Map.Entry<String, Double>> entryList = new ArrayList<Map.Entry<String, Double>>(myMap.entrySet());
    Collections.sort(entryList, new Comparator<Map.Entry<String, Double>>() {
        @Override
        public int compare(Entry<String, Double> o1, Entry<String, Double> o2) {
            return o1.getValue().compareTo(o2.getValue());
        }
    });


Answer 3:

你可以刷卡键和值。 例如

        String[] k = {"Elena", "Thomas", "Hamilton", "Suzie", "Phil"};
        int[] v = {341, 273, 278, 329, 445};
        TreeMap<Integer,String>a=new TreeMap();
        for (int i = 0; i < k.length; i++) 
           a.put(v[i],k[i]);            
        System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());
        a.remove(a.firstEntry().getKey());
        System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());


文章来源: Java TreeMap Comparator