通过单独的参数而不是键对集合中的对象进行排序

问题描述 投票:0回答:1

给定一个名为“SortableRecord”的类,它具有一个用于确定集合中唯一性的 ID 和一个用于确定集合中顺序的值,我如何实现以下目标:

SortedSet<SortableRecord> coll = new TreeSet<>();
coll.add(new SortableRecord("a", 10.0));
coll.add(new SortableRecord("a", 11.0));
coll.add(new SortableRecord("a", 300.0));
coll.add(new SortableRecord("b", 11.0));
coll.add(new SortableRecord("b", 41.0));

assertEquals(2, coll.size());

集合中只能有两个对象。 ID 为

b
的对象应该排在第一位,因为它的值为
41
并且对象
a
ID 为
300

java
1个回答
0
投票

你可以做这样的事情(这有点不传统)。这里我们定义了一个扩展的 HashMap 类并重写了 put 方法以确保基于值的排序。

class SortableRecord {
    private String key;
    private double value;

    public SortableRecord(String key, double value) {
        this.key = key;
        this.value = value;
    }

    public String getKey() {
        return key;
    }

    public double getValue() {
        return value;
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof SortableRecord)) {
            return false;
        }
        SortableRecord sortableRecord = (SortableRecord) o;
        return Objects.equals(this.key, sortableRecord.getKey());
    }

    @Override
    public int hashCode() {
        return Objects.hash(this.key);
    }

    @Override
    public String toString() {
        return String.format("key: %s, value: %f", getKey(), getValue());
    }
}

class Main {
public static void main(String[] args) {
    Map<SortableRecord, Double> coll = new HashMap<SortableRecord, Double>() {
        @Override
        public Double put(SortableRecord key, Double value) {
            Double other = get(key);
            if (other == null || Double.compare(value, other) > 0) {
                super.remove(key);
                return super.put(key, value);
            }
            return other;
        }
    };

    coll.put(new SortableRecord("a", 10.0), 10.0);
    coll.put(new SortableRecord("a", 11.0), 11.0);
    coll.put(new SortableRecord("a", 300.0), 300.0);
    coll.put(new SortableRecord("b", 11.0), 11.0);
    coll.put(new SortableRecord("b", 41.0), 41.0);
    System.out.println(coll.keySet());
   // [key: a, value: 300.000000, key: b, value: 41.000000]
}
}
© www.soinside.com 2019 - 2024. All rights reserved.