简体   繁体   English

如何不丢失TreeMap中具有相同值的元素?

[英]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. 在打印输出中,缺少“ d-> 3”。 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 . 确保将String作为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. 您需要将key包括在内。

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

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