简体   繁体   中英

How to not lose elements with same values from a TreeMap?

class CompoundKey implements Comparable<CompoundKey>{
        String key;
        Integer count;

        public CompoundKey(String key, Integer count){
            this.key = key;
            this.count = count;
        }

        @Override
        public int compareTo(@Nonnull CompoundKey other) {
            return (other.count.compareTo(this.count));
        }
    }

    public static void main(String[] args) {

        Map<CompoundKey, Integer> map = new TreeMap<>();
        map.put(new CompoundKey("a", 3), 3);
        map.put(new CompoundKey("b", 1), 1);
        map.put(new CompoundKey("c", 8), 8);
        map.put(new CompoundKey("d", 3), 3);
        map.put(new CompoundKey("e", 9), 9);

        for (CompoundKey key : map.keySet()) {
            System.out.println(key.key + "->" + map.get(key));
        }
    }

This will print out as below:

e->9
c->8
a->3
b->1

In the print out, the 'd->3' is missing. The purpose of this implementation is to create a map sorted by value when element is inserted (I don't need an implementation that will sort the map after all are inserted).

Is there some minor modification of my code to not lose the element with duplicate values? In the case of two duplicate values, the sorting order can be random.

Be sure to factor in the String as part of your Comparable . For instance (your exact logic may want to vary):

public int compareTo(CompoundKey other) {
    return other.count.compareTo(this.count) + other.key.compareTo(this.key);
}

Because it only looks at numbers right now, it will only ever count numerals as being the natural order. You need to include key as a part of this.

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