在地图中的自定义排序顺序,独立于身份



我有四个信息(a,b,c,d(在一起(例如数据库表中的列(。

A和B的组合是唯一的(例如数据库表中的主要键(

class MyClass {
    private String a, b, c, d; //getters & setters omitted
}
class Key {
    private String a, b; //getters & setters & equals & hashcode omitted
    public int compareTo(Object obj) {
        Key key2 = (Key) obj;
        if (!this.a.equals(key2.a))
            return this.a.compareTo(key2.a);
        else
            return this.b.compareTo(key2.b);
    }
}
class Main {
    private Map<Key, MyClass> map = new TreeMap();
    void populateMap() {
        for each item in the source {
            map.put new Key(a, b), new MyClass(a, b, c, d);
        }
    }
}   

当我在此地图上迭代时,排行首先按场A进行排序,然后按b进行排序。但是我想通过a-> c-> b。

订购

我可以将C添加到我的密钥类中,并相应地修改CompareTo函数。但这感觉是错误的。钥匙是标识符。不需要C识别一行。

我应该如何修改此代码,以便(a,b(是标识符(等于hashCode的标识符是基于基于的(。但是我的地图将信息存储在a-> c-> b?

的顺序中

当您在Java中排序某些东西时,您需要的是两件事:

  • 对象必须为可比性
  • 比较比较对的对象

有了这两件事,您可以做任何您想做的事情:

public class MyClass implements Comparable<MyClass> {
@Ovveride
public int compare(MyClass other) {
    if(this.a.compareTo(other.getA()) != 0)
      return this.a.compareTo(other.getA());
    if(this.c.compareTo(other.getC()) != 0)
      return this.c.compareTo(other.getC());
    return return this.b.compareTo(other.getB());
}
}

在主要类中

// you can sort only Collections so let's say you want to sort values
Collections.sort(mapValues, new Comparator<MyClass> () {
    @Ovveride
    public int compareTo(MyClass c1, MyClass c2) {
       return c1.compare(c2);
    }
});

正如我说的那样,您只能按键自然排序和treemap订购(如果键是可比的,请考虑将信息存储在列表/设置或放置中,然后像我之前写的那样检索您的值。如果您想订购put,您需要通过每个元素(a,b,c(,但请记住,在每个股票后进行排序不是一个好习惯。

如果要对地图的条目(Map.Entry<Key, MyClass>(进行排序,则可以使用compairingByValue

 map.entrySet().stream().sorted(comparingByValue());

并在MyClass中实现compareTo方法,该方法按所需的顺序排序,a-> c-> b。

最新更新