简体   繁体   中英

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.

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. Please note that the order of "0"'s at the end is then random, depending on the sorting algorithm.

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

Just realized, that you want to sort on map values rather then keys . 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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