简体   繁体   English

Java中按多个字段排序的最有效方法

[英]Most efficient way to sort by multiple fields in Java

I'm working on a project where I have a table in memory, for example: 我正在一个项目中,我的内存中有一个表,例如:

field1    field2    field3    field4    field5
somevalue somevalue somevalue somevalue somevalue
somevalue somevalue somevalue somevalue somevalue
    .
    . 
    .
    .
    v

What is the best way to write a function that would allow a user to specify some non-predetermined permutation of fields by which to sort? 编写允许用户指定排序字段的某些非预定排列的函数的最佳方法是什么? (ex./ sort by field2, then field1, then field5). (例如/按field2,然后按field1,然后按field5排序)。 The best method I thought of so far is a recursive function, but it gets ugly pretty quick, especially with creating and managing 'subgroups' of rows within each column. 到目前为止,我想到的最好的方法是递归函数,但是它很快就会变得很丑陋,尤其是在创建和管理每列中的行的“子组”时。 Can somebody point me in a more efficient direction before I commit to this convoluted approach? 在我采取这种复杂的方法之前,有人可以指出我的方向吗?

By the way, my table is stored as a list of arrays. 顺便说一句,我的表存储为数组列表。

The key thing to realize here is that your search algorithm always stays exactly the same. 在这里要实现的关键是您的搜索算法始终保持完全相同。 The only thing that changes is your actual comparison function. 唯一改变的是您的实际比较功能。

I would recommend using a standard sort in the Arrays or Collections class, but writing your own custom Comparable class or Comparator , whose compare method will use the data the user supplies. 我建议在ArraysCollections类中使用标准排序,但要编写自己的自定义Comparable类或Comparator ,其compare方法将使用用户提供的数据。 This is actually kind of interesting - I've only ever written Comparable classes that use fixed data, but this is exactly a use case for them. 这实际上很有趣-我只写过使用固定数据的Comparable类,但这恰恰是它们的用例。

All you need to do is write the function 您需要做的就是编写函数

public int compare(Row row1, Row row2) {
    // iterate over the columns *in order of the user-supplied priority*
    // return appropriately
}

Here's documentation on the Comparable class . 这是Comparable类的文档

And Comparator . 和比较器

Which one you need depends on what you're implementing, I forget the details but should be straightforward. 您需要哪一个取决于您要实现的内容,我忘记了细节,但是应该很简单。

The key #2 thing here is that you can instantiate your ColumnPrioritiesComparable class before the priorities are set. 这里的关键2件事是,您可以设置优先级之前实例化ColumnPrioritiesComparable类。 eg 例如

class ColPriComp implements Comparable<ColPriComp> {
    private volatile int[] priorities; // possibly static, or obtained some other way,
    // so there's only one shared among all classes

    @Override
    public int compareTo(ColPriComp other) {
        // use "priorities" to do the comparison
    }

    public void setPriorities(int[] newPriorities) {
        this.priorities = newPriorities;
    }
}

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

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