简体   繁体   English

将元素放在TreeMap的末尾

[英]put element at the end of a TreeMap

我有一个树形图,其中我按升序对元素进行了排序,例如0、1、2、3等。这些元素按其值排序,即0、1,2等是值。我使用了比较器对它们进行排序。我想保留这个顺序,除了我想将0值的元素放在map的末尾。

As you already said, your TreeMap is sorted, so it would be completely senseless to allow you to append an element at the "end", even though TreeMaps just don't work that way. 正如您已经说过的那样,TreeMap是经过排序的,因此即使TreeMap不能那样工作,允许您在“ end”末尾添加元素也是完全没有意义的。

What you could do is configure your Comparator in a way that it decides that "0" is the largest element, so he will sort all "0" to the very end. 您可以做的是配置比较器,使其确定“ 0”是最大的元素,因此他会将所有“ 0”排序到最后。 Please note that the order of "0"'s at the end is then random, depending on the sorting algorithm. 请注意,最后的“ 0”顺序是随机的,具体取决于排序算法。

您可以修改比较器并将0视为最大数字

Just realized, that you want to sort on map values rather then keys . 刚意识到,您想对地图而不是key进行排序。 The comparator does not get values which makes it a bit more complicated. 比较器无法获取值,这使其变得更加复杂。 The new approach uses a second (unsorted) map that just collects all values and can be used by the comparator to lookup the values for the keys: 方法使用第二个(未排序的)映射,该映射仅收集所有值,并且可以由比较器用来查找键的值:

private static Map<String, Integer> helper = new HashMap<String, Integer>();

private static Comparator<String> myComparator 
                  = new Comparator<String>() {
  public int compare(String s1, String s2) {
    Integer i1 = helper.get(s1);
    Integer i2 = helper.get(s2);

    if (i1 == 0) return  1; //  i1 > i2
    if (i2 == 0) return -1; //  i1 < i2

    return i1.compareTo(i2);
  } 
};

public static void main (String[] args) throws java.lang.Exception {
  helper.put("minus one", -1);
  helper.put("zero", 0);
  helper.put("one", 1);
  helper.put("very much", Integer.MAX_VALUE);
  helper.put("nothing", 0);
  helper.put("null", 0);

  Map<String, Integer> map = new TreeMap<String, Integer>(myComparator);
  map.putAll(helper);

  for(Map.Entry<String, Integer> entry:map.entrySet()) {
    System.out.printf("%s = %s%n", entry.getKey(), entry.getValue());
  }
}

The output is: 输出为:

minus one = -1
one = 1
very much = 2147483647
nothing = 0
zero = 0
null = 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM