使用2个条件在Java中对列表进行排序

时间:2021-03-27 17:13:19

I have a list of objects. Each object contains a String and a Date (amongst others).

我有一个对象列表。每个对象都包含一个String和一个Date(以及其他对象)。

I want to first sort by the String and then by the Date.

我想首先按字符串排序,然后按日期排序。

How could this be done in the cleanest way possible?

怎么可能以最干净的方式完成?

Thanks!

谢谢!

Krt_Malta

Krt_Malta

6 个解决方案

#1


16  

Given an object class that looks like this:

给定一个如下所示的对象类:

public class MyObject {
    public String getString() { ... }
    public Date getDate() { ... }
    ...
}

Write a custom comparator class like so:

编写自定义比较器类,如下所示:

public class ObjectComparator implements Comparator{

    public int compare(Object obj1, Object obj2) {
        MyObject myObj1 = (MyObject)obj1;
        MyObject myObj2 = (MyObject)obj2;
        stringResult = myObj1.getString().compareTo(myObj2.getString());
        if (stringResult == 0) {
            // Strings are equal, sort by date
            return myObj1.getDate().compareTo(myObj2.getDate());
        }
        else {
            return stringResult;
        }
    }
}

Then sort as follows:

然后排序如下:

Collections.sort(objectList, new ObjectComparator());

#2


14  

With Java 8, this is really easy. Given

使用Java 8,这非常简单。特定

class MyClass {
    String getString() { ... }
    Date getDate() { ... }
}

You can easily sort a list as follows:

您可以按如下方式轻松对列表进行排序:

List<MyClass> list = ...
list.sort(Comparator.comparing(MyClass::getString).thenComparing(MyClass::getDate));

#3


6  

Implement a custom Comparator, using a compare(a,b) method like the following:

使用比较(a,b)方法实现自定义Comparator,如下所示:

Plain Java:

普通Java:

 public int compare(YourObject o1, YourObject o2) {
    int result = o1.getProperty1().compareTo(o2.getProperty1()));
    if(result==0) result = o1.getProperty2().compareTo(o2.getProperty2());
    return result;
 }

With Guava (using ComparisonChain):

使用Guava(使用ComparisonChain):

public int compare(YourObject o1, YourObject o2) {
    return ComparisonChain.start()
      .compare(o1.getProperty1(), o2.getProperty1())
      .compare(o1.getProperty2(), o2.getProperty2())
      .result();
 }

With Commons / Lang (using CompareToBuilder):

使用Commons / Lang(使用CompareToBuilder):

public int compare(YourObject o1, YourObject o2) {
    return new CompareToBuilder()
      .append(o1.getProperty1(), o2.getProperty1())
      .append(o1.getProperty2(), o2.getProperty2())
      .toComparison();
 }

(All three versions are equivalent, but the plain Java version is the most verbose and hence most error-prone one. All three solutions assume that both o1.getProperty1() and o1.getProperty2() implement Comparable).

(所有三个版本都是等价的,但普通的Java版本是最冗长的,因此最容易出错。所有三个解决方案都假设o1.getProperty1()和o1.getProperty2()都实现了Comparable)。

(Taken from this previous answer of mine)

(取自我此前的答案)


now do Collections.sort(yourList, yourComparator)

现在做Collections.sort(yourList,yourComparator)

#4


6  

The Comparators answer is correct but incomplete.

比较器的答案是正确但不完整的。

StringAndDateComparator implements Comparator<MyObject> {

   public int compare(MyObject first, MyObject second) {
        int result = first.getString().compareTo(second.getString());
        if (result != 0) {
            return result;
        }
        else {
            return first.getDate().compareTo(second.getDate());
        }
}

GlazedLists has a nice utility method to chain together different comparators to save you from writing this boilerplate. See the chainComparators method for more information.

GlazedLists有一个很好的实用方法可以将不同的比较器链接在一起,以免您编写此样板文件。有关更多信息,请参阅chainComparators方法。

#5


1  

Try this method:

试试这个方法:

Collections.sort(list, comparator)

Collections.sort(列表,比较器)

You should of course have a custom Comparator implementation for your object, as stated by Manoj.

您当然应该为您的对象提供自定义Comparator实现,如Manoj所述。

#6


1  

Using java 8 and parallel sorting technique, we can also achieve this as follows:

使用java 8和并行排序技术,我们也可以实现如下:

List<Employee> empss  = getEmployees();
Comparator<Employee> combinedComparator = Comparator.comparing(Employee::getFName)
                                                    .thenComparing(Employee::getLName);
Employee[] emppArr = employees.toArray(new Employee[empss.size()]);

//Parallel sorting
Arrays.parallelSort(emppArr, combinedComparator);

#1


16  

Given an object class that looks like this:

给定一个如下所示的对象类:

public class MyObject {
    public String getString() { ... }
    public Date getDate() { ... }
    ...
}

Write a custom comparator class like so:

编写自定义比较器类,如下所示:

public class ObjectComparator implements Comparator{

    public int compare(Object obj1, Object obj2) {
        MyObject myObj1 = (MyObject)obj1;
        MyObject myObj2 = (MyObject)obj2;
        stringResult = myObj1.getString().compareTo(myObj2.getString());
        if (stringResult == 0) {
            // Strings are equal, sort by date
            return myObj1.getDate().compareTo(myObj2.getDate());
        }
        else {
            return stringResult;
        }
    }
}

Then sort as follows:

然后排序如下:

Collections.sort(objectList, new ObjectComparator());

#2


14  

With Java 8, this is really easy. Given

使用Java 8,这非常简单。特定

class MyClass {
    String getString() { ... }
    Date getDate() { ... }
}

You can easily sort a list as follows:

您可以按如下方式轻松对列表进行排序:

List<MyClass> list = ...
list.sort(Comparator.comparing(MyClass::getString).thenComparing(MyClass::getDate));

#3


6  

Implement a custom Comparator, using a compare(a,b) method like the following:

使用比较(a,b)方法实现自定义Comparator,如下所示:

Plain Java:

普通Java:

 public int compare(YourObject o1, YourObject o2) {
    int result = o1.getProperty1().compareTo(o2.getProperty1()));
    if(result==0) result = o1.getProperty2().compareTo(o2.getProperty2());
    return result;
 }

With Guava (using ComparisonChain):

使用Guava(使用ComparisonChain):

public int compare(YourObject o1, YourObject o2) {
    return ComparisonChain.start()
      .compare(o1.getProperty1(), o2.getProperty1())
      .compare(o1.getProperty2(), o2.getProperty2())
      .result();
 }

With Commons / Lang (using CompareToBuilder):

使用Commons / Lang(使用CompareToBuilder):

public int compare(YourObject o1, YourObject o2) {
    return new CompareToBuilder()
      .append(o1.getProperty1(), o2.getProperty1())
      .append(o1.getProperty2(), o2.getProperty2())
      .toComparison();
 }

(All three versions are equivalent, but the plain Java version is the most verbose and hence most error-prone one. All three solutions assume that both o1.getProperty1() and o1.getProperty2() implement Comparable).

(所有三个版本都是等价的,但普通的Java版本是最冗长的,因此最容易出错。所有三个解决方案都假设o1.getProperty1()和o1.getProperty2()都实现了Comparable)。

(Taken from this previous answer of mine)

(取自我此前的答案)


now do Collections.sort(yourList, yourComparator)

现在做Collections.sort(yourList,yourComparator)

#4


6  

The Comparators answer is correct but incomplete.

比较器的答案是正确但不完整的。

StringAndDateComparator implements Comparator<MyObject> {

   public int compare(MyObject first, MyObject second) {
        int result = first.getString().compareTo(second.getString());
        if (result != 0) {
            return result;
        }
        else {
            return first.getDate().compareTo(second.getDate());
        }
}

GlazedLists has a nice utility method to chain together different comparators to save you from writing this boilerplate. See the chainComparators method for more information.

GlazedLists有一个很好的实用方法可以将不同的比较器链接在一起,以免您编写此样板文件。有关更多信息,请参阅chainComparators方法。

#5


1  

Try this method:

试试这个方法:

Collections.sort(list, comparator)

Collections.sort(列表,比较器)

You should of course have a custom Comparator implementation for your object, as stated by Manoj.

您当然应该为您的对象提供自定义Comparator实现,如Manoj所述。

#6


1  

Using java 8 and parallel sorting technique, we can also achieve this as follows:

使用java 8和并行排序技术,我们也可以实现如下:

List<Employee> empss  = getEmployees();
Comparator<Employee> combinedComparator = Comparator.comparing(Employee::getFName)
                                                    .thenComparing(Employee::getLName);
Employee[] emppArr = employees.toArray(new Employee[empss.size()]);

//Parallel sorting
Arrays.parallelSort(emppArr, combinedComparator);

相关文章