java 基于两列的Java排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6878050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 17:42:45  来源:igfitidea点击:

Java sort based on two columns

javasortingmultiple-columns

提问by Mat B.

Lets say I have table like this:

假设我有这样的表:

 String | Int1 | Int2
 "foo"    5      0
 "faa"    4      1
 "zaa"    0      1
 "zoo"    4      2
 "laa"    4      3
 "loo"    1      4

What I would like to get is table like this:

我想得到的是这样的表:

 String | Int1 | Int2
 "foo"    5      0
 "laa"    4      3
 "zoo"    4      2
 "faa"    4      1
 "loo"    1      4
 "zaa"    0      1

First thing that happens is sort based on column Int1.

发生的第一件事是根据 column 进行排序Int1

Second thing that happens is sort of based on column Int2but only on rows that have same numbers in column Int1

发生的第二件事是基于列,Int2但仅基于列中具有相同数字的行Int1

How should I approach this problem without using any database engine?

我应该如何在不使用任何数据库引擎的情况下解决这个问题?

采纳答案by Jon Skeet

You'd normally do this with a List<Item>where Itemis a type containing all three values ("foo", 5, 0 for the first row, for example).

您通常会使用List<Item>whereItem是包含所有三个值的类型(例如,第一行的 "foo", 5, 0 )。

You'd then write a Comparator<Item>which compared the Int1 values of the two Itemobjects presented to it in compare, and if that gave a definite answer, returned that answer... and otherwise compared the Int2 values.

然后,您将编写一个Comparator<Item>比较 中Item呈现给它的两个对象的 Int1 值compare,如果给出了明确的答案,则返回该答案......否则比较 Int2 值。

回答by Kal

I'm assuming you have an object that has a String with 2 ints?

我假设您有一个包含 2 个整数的字符串的对象?

The easiest way to do this is to make the object implement Comparableand implement the compareTo()method. Or you can pass a Comparator to Collections.sort(yourListOfObjects, yourCustomComparator)

最简单的方法是让对象实现Comparable并实现compareTo()方法。或者您可以将 Comparator 传递给Collections.sort(yourListOfObjects, yourCustomComparator)

The compareTo() method will compare the first int first and if they are equal compare the second ints.

compareTo() 方法将首先比较第一个 int,如果它们相等,则比较第二个 int。

@Override
public int compareTo(MyObject o) {
    // compare int1s .. if equal, compare int2s and return 0,1 or -1
}

Here is a helpful link

这是一个有用的链接

http://download.oracle.com/javase/tutorial/collections/interfaces/order.html

http://download.oracle.com/javase/tutorial/collections/interfaces/order.html

回答by Joshua Kaplan

It's rather unclear what you mean by table. But in the general case, you sort data in Java by using a Comparatoror making your data structure implement Comparable. In your case you would create a simple data structure that encapsulates a row in your table, and then create a Comparatorfor the row data structure or have it implement Comparable.

你说的桌子是什么意思还不清楚。但在一般情况下,您可以通过使用Comparator或使您的数据结构实现来对 Java 中的数据进行排序Comparable。在您的情况下,您将创建一个简单的数据结构来封装表中的一行,然后Comparator为行数据结构创建一个或让它实现Comparable.

For example

例如

public class Row implements Comparable<Row> {
    public final String theString;
    public final int int1;
    public final int int2;

    public Row(String theString, int int1, int int2) {
        this.theString = theString;
        this.int1 = int1;
        this.int2 = int2;
   }

   public int compareTo(Row other) {
       if(this.int1 == other.int1) {
           return new Integer(this.int2).compareTo(other.int2);
       }

       return new Integer(this.int1).compareTo(other.int1);
   }
}

Then you would create a List<Row>and use java.util.Collections.sort(List<?>)to sort your data.

然后您将创建一个List<Row>并用于java.util.Collections.sort(List<?>)对您的数据进行排序。

回答by tskuzzy

Well first define what you mean by a "table".

那么首先定义你所说的“表”是什么意思。

I would wrap each row within an object Rowand keep an array of these Rows. Then you can either implement the Comparable<Row>interface or write your own Comparator<Row>.

我会将每一行包装在一个对象中Row并保留这些Rows的数组。然后您可以实现Comparable<Row>接口或编写自己的Comparator<Row>.

So either:

所以要么:

...
class Row implements Comparable<Row> {
    String s;
    int int1, int2;

    ...

    public int compareTo( Row r ) {
        if( int1 != r.int1 ) return int1-r.int1;
        else return int2-r.int2;
    }
}

And call Arrays.sort(rows);

并打电话 Arrays.sort(rows);

Or you can do this:

或者你可以这样做:

Arrays.sort(rows, new Comparator<Row>() {
    public int compare( Row r1, Row r2 ) {
        if( r1.int1 != r2.int1 ) return r1.int1-r2.int1;
        else return r1.int2-r2.int2;
    }
});

where rowsis a Row[].

哪里rowsRow[].

回答by tskuzzy

If only Java supported lambdas ... this is trivial in so many languages.

如果只有 Java 支持 lambdas ......这在很多语言中都是微不足道的。

But, hmm, let's see. Here are two general approaches (there are many different variations of these themes):

但是,嗯,让我们看看。以下是两种通用方法(这些主题有许多不同的变体):

  1. Create a new type with the members in question
  2. Make the type implement Comparable(e.g. "compareTo")
  3. Put elements of this new type into an Array or List (perhaps List<NewType>)
  4. Use Arrays.sortor Collections.sort(or similar)
  1. 使用相关成员创建一个新类型
  2. 使类型实现Comparable(例如“compareTo”)
  3. 将这种新类型的元素放入数组或列表中(可能List<NewType>
  4. 使用Arrays.sortCollections.sort(或类似的)

Or,

或者,

  1. Create a nested array or List (perhaps List<List<Object>>)
  2. Use Arrays.sortor Collections.sort(or similar) using the form that takes in a Comparator
  1. 创建嵌套数组或列表(可能List<List<Object>>
  2. 使用Arrays.sortCollections.sort(或类似的)使用形式Comparator

Happy coding.

快乐编码。

回答by user802421

Something like this?

像这样的东西?

public class Item implements Comparable<Item> {
    private String s;
    private Integer int1;
    private Integer int2;

    @Override
    public int compareTo(Item o) {
        int compare = int1.compareTo(o.int1);
        return compare != 0 ? compare : int2.compareTo(o.int2);
    }
}

回答by James Anton

I would use a CompareToBuilder inside a Comparator implementation.

我会在 Comparator 实现中使用 CompareToBuilder。

Example usage,

示例用法,

    new Comparator<YourObjectType>() {
            @Override
            public int compare(YourObjectType o1, YourObjectType o2) {
                return new CompareToBuilder()
                   .append(o1.firstFieldToCompare, o2.firstFieldToCompare)
                   .append(o1.secondFieldToCompare, o2.secondFieldToCompare)
                   .toComparison();
            }
        }