Azfar
Azfar

Reputation: 317

put element at the end of a TreeMap

i have a Tree Map in which i have sorted elements in ascending order like 0,1,2,3 etc.These elements are sorted on their values i.e 0,1,2 etc are values.I have used a comparator to sort them..I want to retain this order except that i want to put element with 0 value at the end of map.How to do it?

Upvotes: 1

Views: 2313

Answers (3)

Andreas Dolk
Andreas Dolk

Reputation: 114767

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

Upvotes: 1

Jan Gr&#228;fen
Jan Gr&#228;fen

Reputation: 314

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.

Upvotes: 5

blitzqwe
blitzqwe

Reputation: 2040

You can modify your Comparator and treat 0 as the largest number

Upvotes: 1

Related Questions