如何通过多个字段比较对象

时间:2008-12-15 19:56:44

标签: java oop

假设您有一些具有多个字段的对象,可以通过以下方式进行比较:

public class Person {

    private String firstName;
    private String lastName;
    private String age;

    /* Constructors */

    /* Methods */

}

所以在这个例子中,当你询问是否:

a.compareTo(b) > 0

你可能会问b的名字是否在b之前,或者a是否早于b等...

在不增加不必要的混乱或开销的情况下,在这些类型的对象之间进行多重比较的最简洁方法是什么?

  • java.lang.Comparable界面仅允许按一个字段进行比较
  • 在我看来,添加大量的比较方法(例如compareByFirstName()compareByAge()等等)是混乱的。

那么最好的方法是什么?

23 个答案:

答案 0 :(得分:308)

使用Java 8:

Comparator.comparing((Person p)->p.firstName)
          .thenComparing(p->p.lastName)
          .thenComparingInt(p->p.age);

如果您有访问方法:

Comparator.comparing(Person::getFirstName)
          .thenComparing(Person::getLastName)
          .thenComparingInt(Person::getAge);

如果一个类实现了Comparable,则可以在compareTo方法中使用这样的比较器:

@Override
public int compareTo(Person o){
    return Comparator.comparing(Person::getFirstName)
              .thenComparing(Person::getLastName)
              .thenComparingInt(Person::getAge)
              .compare(this, o);
}

答案 1 :(得分:146)

您应该实施Comparable <Person>。假设所有字段都不为空(为简单起见),该年龄为int,并且比较排名为first,last,age,compareTo方法非常简单:

public int compareTo(Person other) {
    int i = firstName.compareTo(other.firstName);
    if (i != 0) return i;

    i = lastName.compareTo(other.lastName);
    if (i != 0) return i;

    return Integer.compare(age, other.age);
}

答案 2 :(得分:70)

您可以实现一个比较两个Comparator对象的Person,您可以根据需要检查多个字段。您可以在比较器中放入一个变量,告诉它要比较哪个字段,尽管编写多个比较器可能更简单。

答案 3 :(得分:58)

(来自House of Code

凌乱而错综复杂:手工排序

Collections.sort(pizzas, new Comparator<Pizza>() {  
    @Override  
    public int compare(Pizza p1, Pizza p2) {  
        int sizeCmp = p1.size.compareTo(p2.size);  
        if (sizeCmp != 0) {  
            return sizeCmp;  
        }  
        int nrOfToppingsCmp = p1.nrOfToppings.compareTo(p2.nrOfToppings);  
        if (nrOfToppingsCmp != 0) {  
            return nrOfToppingsCmp;  
        }  
        return p1.name.compareTo(p2.name);  
    }  
});  

这需要大量的打字,维护并且容易出错。

反射方式:使用BeanComparator进行排序

ComparatorChain chain = new ComparatorChain(Arrays.asList(
   new BeanComparator("size"), 
   new BeanComparator("nrOfToppings"), 
   new BeanComparator("name")));

Collections.sort(pizzas, chain);  

显然,这更简洁,但更容易出错,因为您通过使用字符串而失去了对字段的直接引用。现在,如果重命名一个字段,编译器甚至不会报告问题。此外,由于此解决方案使用反射,因此排序速度要慢得多。

到达目的地:使用Google Guava的ComparisonChain进行排序

Collections.sort(pizzas, new Comparator<Pizza>() {  
    @Override  
    public int compare(Pizza p1, Pizza p2) {  
        return ComparisonChain.start().compare(p1.size, p2.size).compare(p1.nrOfToppings, p2.nrOfToppings).compare(p1.name, p2.name).result();  
        // or in case the fields can be null:  
        /* 
        return ComparisonChain.start() 
           .compare(p1.size, p2.size, Ordering.natural().nullsLast()) 
           .compare(p1.nrOfToppings, p2.nrOfToppings, Ordering.natural().nullsLast()) 
           .compare(p1.name, p2.name, Ordering.natural().nullsLast()) 
           .result(); 
        */  
    }  
});  

这样做要好得多,但是对于最常见的用例需要一些样板代码:默认情况下,null值的值应该更少。对于null-fields,你必须向Guava提供一个额外的指令,在这种情况下该做什么。如果您想要执行特定的操作,这是一种灵活的机制,但通常您需要默认情况(即1,a,b,z,null)。

使用Apache Commons CompareToBuilder进行排序

Collections.sort(pizzas, new Comparator<Pizza>() {  
    @Override  
    public int compare(Pizza p1, Pizza p2) {  
        return new CompareToBuilder().append(p1.size, p2.size).append(p1.nrOfToppings, p2.nrOfToppings).append(p1.name, p2.name).toComparison();  
    }  
});  

与Guava的ComparisonChain一样,此库类可以在多个字段上轻松排序,但也定义了空值的默认行为(即.1,a,b,z,null)。但是,除非您提供自己的比较器,否则您也无法指定任何其他内容。

因此

最终,它归结为味道和灵活性的需求(Guava的ComparisonChain)与简洁的代码(Apache的CompareToBuilder)。

奖金方法

我找到了一个很好的解决方案,它在MultiComparator中按优先顺序on CodeReview组合了多个比较器:

class MultiComparator<T> implements Comparator<T> {
    private final List<Comparator<T>> comparators;

    public MultiComparator(List<Comparator<? super T>> comparators) {
        this.comparators = comparators;
    }

    public MultiComparator(Comparator<? super T>... comparators) {
        this(Arrays.asList(comparators));
    }

    public int compare(T o1, T o2) {
        for (Comparator<T> c : comparators) {
            int result = c.compare(o1, o2);
            if (result != 0) {
                return result;
            }
        }
        return 0;
    }

    public static <T> void sort(List<T> list, Comparator<? super T>... comparators) {
        Collections.sort(list, new MultiComparator<T>(comparators));
    }
}

Ofcourse Apache Commons Collections已经为此提供了一个实用工具:

ComparatorUtils.chainedComparator(comparatorCollection)

Collections.sort(list, ComparatorUtils.chainedComparator(comparators));

答案 4 :(得分:21)

@Patrick要连续排序多个字段,请尝试ComparatorChain

  

ComparatorChain是一个比较器,它按顺序包装一个或多个比较器。 ComparatorChain按顺序调用每个Comparator,直到1)任何单个Comparator返回非零结果(然后返回该结果),或2)ComparatorChain耗尽(并返回零)。这种类型的排序与SQL中的多列排序非常相似,这个类允许Java类在排序List时模拟这种行为。

     

为了进一步促进类似SQL的排序,列表中任何单个比较器的顺序都可以反转。

     

在调用compare(Object,Object)之后调用添加新比较器或更改上升/下降排序的方法将导致UnsupportedOperationException。但是,请注意不要更改基础的比较器列表或定义排序顺序的BitSet。

     

ComparatorChain的实例未同步。该类在构造时不是线程安全的,但在所有设置操作完成后执行多次比较是线程安全的。

答案 5 :(得分:19)

您可以随时考虑的另一个选项是Apache Commons。它提供了很多选择。

import org.apache.commons.lang3.builder.CompareToBuilder;

例如:

public int compare(Person a, Person b){

   return new CompareToBuilder()
     .append(a.getName(), b.getName())
     .append(a.getAddress(), b.getAddress())
     .toComparison();
}

答案 6 :(得分:11)

您还可以查看实现Comparator的Enum。

http://tobega.blogspot.com/2008/05/beautiful-enums.html

e.g。

Collections.sort(myChildren, Child.Order.ByAge.descending());

答案 7 :(得分:7)

对于那些能够使用Java 8流API的人来说,有一种更简洁的方法,这里有详细记录: Lambdas and sorting

我正在寻找相当于C#LINQ:

.ThenBy(...)

我在比较器上找到了Java 8中的机制:

.thenComparing(...)

所以这是演示算法的片段。

    Comparator<Person> comparator = Comparator.comparing(person -> person.name);
    comparator = comparator.thenComparing(Comparator.comparing(person -> person.age));

查看上面的链接,了解更简洁的方法以及有关Java类型推断如何使其与LINQ相比更加笨拙的解释。

以下是完整的单元测试供参考:

@Test
public void testChainedSorting()
{
    // Create the collection of people:
    ArrayList<Person> people = new ArrayList<>();
    people.add(new Person("Dan", 4));
    people.add(new Person("Andi", 2));
    people.add(new Person("Bob", 42));
    people.add(new Person("Debby", 3));
    people.add(new Person("Bob", 72));
    people.add(new Person("Barry", 20));
    people.add(new Person("Cathy", 40));
    people.add(new Person("Bob", 40));
    people.add(new Person("Barry", 50));

    // Define chained comparators:
    // Great article explaining this and how to make it even neater:
    // http://blog.jooq.org/2014/01/31/java-8-friday-goodies-lambdas-and-sorting/
    Comparator<Person> comparator = Comparator.comparing(person -> person.name);
    comparator = comparator.thenComparing(Comparator.comparing(person -> person.age));

    // Sort the stream:
    Stream<Person> personStream = people.stream().sorted(comparator);

    // Make sure that the output is as expected:
    List<Person> sortedPeople = personStream.collect(Collectors.toList());
    Assert.assertEquals("Andi",  sortedPeople.get(0).name); Assert.assertEquals(2,  sortedPeople.get(0).age);
    Assert.assertEquals("Barry", sortedPeople.get(1).name); Assert.assertEquals(20, sortedPeople.get(1).age);
    Assert.assertEquals("Barry", sortedPeople.get(2).name); Assert.assertEquals(50, sortedPeople.get(2).age);
    Assert.assertEquals("Bob",   sortedPeople.get(3).name); Assert.assertEquals(40, sortedPeople.get(3).age);
    Assert.assertEquals("Bob",   sortedPeople.get(4).name); Assert.assertEquals(42, sortedPeople.get(4).age);
    Assert.assertEquals("Bob",   sortedPeople.get(5).name); Assert.assertEquals(72, sortedPeople.get(5).age);
    Assert.assertEquals("Cathy", sortedPeople.get(6).name); Assert.assertEquals(40, sortedPeople.get(6).age);
    Assert.assertEquals("Dan",   sortedPeople.get(7).name); Assert.assertEquals(4,  sortedPeople.get(7).age);
    Assert.assertEquals("Debby", sortedPeople.get(8).name); Assert.assertEquals(3,  sortedPeople.get(8).age);
    // Andi     : 2
    // Barry    : 20
    // Barry    : 50
    // Bob      : 40
    // Bob      : 42
    // Bob      : 72
    // Cathy    : 40
    // Dan      : 4
    // Debby    : 3
}

/**
 * A person in our system.
 */
public static class Person
{
    /**
     * Creates a new person.
     * @param name The name of the person.
     * @param age The age of the person.
     */
    public Person(String name, int age)
    {
        this.age = age;
        this.name = name;
    }

    /**
     * The name of the person.
     */
    public String name;

    /**
     * The age of the person.
     */
    public int age;

    @Override
    public String toString()
    {
        if (name == null) return super.toString();
        else return String.format("%s : %d", this.name, this.age);
    }
}

答案 8 :(得分:6)

为这样的用例手动编写Comparator是一个可怕的解决方案IMO。这种临时方法有许多缺点:

  • 无代码重用。违反DRY。
  • 样板。
  • 错误的可能性增加。

那么解决方案是什么?

首先是一些理论。

让我们用A来表示“Ord A支持比较”这一命题。 (从程序的角度来看,您可以将Ord A视为包含用于比较两个A的逻辑的对象。是的,就像Comparator一样。)

现在,如果Ord AOrd B,那么他们的复合(A, B)也应该支持比较。即Ord (A, B)。如果是Ord AOrd BOrd C,那么Ord (A, B, C)

我们可以将这个论点扩展到任意的arity,然后说:

Ord A, Ord B, Ord C, ..., Ord ZOrd (A, B, C, .., Z)

我们称之为声明1。

复合材料的比较将像您在问题中描述的那样工作:首先尝试第一次比较,然后是下一次比较,然后是下一次,依此类推。

这是我们解决方案的第一部分。现在是第二部分。

如果你知道Ord A,并知道如何将B转换为A(称之为转化函数f),那么你也可以拥有Ord B }。怎么样?好吧,当要比较两个B个实例时,首先使用A将它们转换为f,然后应用Ord A

在此,我们将转化B → A映射到Ord A → Ord B。这被称为逆变映射(或简称comap)。

Ord A, (B → A) comap Ord B

我们称之为声明2。


现在让我们将其应用于您的示例。

您有一个名为Person的数据类型,其中包含三个String类型的字段。

  • 我们知道Ord String。声明1,Ord (String, String, String)

  • 我们可以轻松地将函数从Person写入(String, String, String)。 (只需返回三个字段。)由于我们知道Ord (String, String, String)Person → (String, String, String),因此我们可以使用comap来获取Ord Person

QED。


如何实施所有这些概念?

好消息是你不必。已存在a library,它实现了本文中描述的所有想法。 (如果您对如何实施这些内容感到好奇,可以look under the hood。)

这就是代码的外观:

Ord<Person> personOrd = 
 p3Ord(stringOrd, stringOrd, stringOrd).comap(
   new F<Person, P3<String, String, String>>() {
     public P3<String, String, String> f(Person x) {
       return p(x.getFirstName(), x.getLastname(), x.getAge());
     }
   }
 );

<强>解释

  • stringOrdOrd<String>类型的对象。这与我们原来的“支持比较”主张相对应。
  • p3Ord是一种采用Ord<A>Ord<B>Ord<C>并返回Ord<P3<A, B, C>>的方法。这对应于陈述1.(P3代表具有三个元素的产品。产品是复合材料的代数术语。)
  • comap对应好,comap
  • F<A, B>代表转换函数A → B
  • p是用于创建产品的工厂方法。
  • 整个表达式对应于陈述2.

希望有所帮助。

答案 9 :(得分:6)

import com.google.common.collect.ComparisonChain;

/**
 * @author radler
 * Class Description ...
 */
public class Attribute implements Comparable<Attribute> {

    private String type;
    private String value;

    public String getType() { return type; }
    public void setType(String type) { this.type = type; }

    public String getValue() { return value; }
    public void setValue(String value) { this.value = value; }

    @Override
    public String toString() {
        return "Attribute [type=" + type + ", value=" + value + "]";
    }

    @Override
    public int compareTo(Attribute that) {
        return ComparisonChain.start()
            .compare(this.type, that.type)
            .compare(this.value, that.value)
            .result();
    }

}

答案 10 :(得分:4)

您可能希望在Person类中定义几种类型的“Comparator”子类,而不是比较方法。这样您就可以将它们传递给标准的集合排序方法。

答案 11 :(得分:3)

如果我们必须基于多个字段对Person对象进行排序,则相同的代码实现在这里。

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Person {

private String firstName;
private String lastName;
private int age;

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}

public Person(String firstName, String lastName, int age) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
}


static class PersonSortingComparator implements Comparator<Person> {

    @Override
    public int compare(Person person1, Person person2) {

        // for first name comparison
        int firstNameCompare = person1.getFirstName().compareTo(person2.getFirstName());

        // for last name comparison
        int lastNameCompare = person1.getLastName().compareTo(person2.getLastName());

        // for last name comparison
        int ageCompare = person1.getAge() - person2.getAge();

        // Now comparing
        if (firstNameCompare == 0) {
            if (lastNameCompare == 0) {
                return ageCompare;
            }
            return lastNameCompare;
        }
        return firstNameCompare;
    }
}

public static void main(String[] args) {
    Person person1 = new Person("Ajay", "Kumar", 27);
    Person person2 = new Person("Ajay","Gupta", 23);
    Person person3 = new Person("Ajay","Kumar", 22);


    ArrayList<Person> persons = new ArrayList<>();
    persons.add(person1);
    persons.add(person2);
    persons.add(person3);


    System.out.println("Before Sorting:\n");
    for (Person person : persons) {
        System.out.println(person.firstName + " " + person.lastName + " " + person.age);
    }

    Collections.sort(persons, new PersonSortingComparator());

    System.out.println("After Sorting:\n");
    for (Person person : persons) {
        System.out.println(person.firstName + " " + person.lastName + " " + person.age);
    }
}

}

答案 12 :(得分:2)

如果用户可能有多种方式订购人,您也可以将多个Comparator设置为常量。大多数排序操作和排序集合都将比较器作为参数。

答案 13 :(得分:2)

如果您的比较算法“聪明”,我认为会更加困惑。我会选择你建议的众多比较方法。

我唯一的例外是平等。对于单元测试,我有必要覆盖.Equals(在.net中),以确定两个对象之间的几个字段是否相等(而不是引用相等)。

答案 14 :(得分:1)

//here threshold,buyRange,targetPercentage are three keys on that i have sorted my arraylist 
final Comparator<BasicDBObject> 

    sortOrder = new Comparator<BasicDBObject>() {
                    public int compare(BasicDBObject e1, BasicDBObject e2) {
                        int threshold = new Double(e1.getDouble("threshold"))
                        .compareTo(new Double(e2.getDouble("threshold")));
                        if (threshold != 0)
                            return threshold;

                        int buyRange = new Double(e1.getDouble("buyRange"))
                        .compareTo(new Double(e2.getDouble("buyRange")));
                        if (buyRange != 0)
                            return buyRange;

                        return (new Double(e1.getDouble("targetPercentage")) < new Double(
                                e2.getDouble("targetPercentage")) ? -1 : (new Double(
                                        e1.getDouble("targetPercentage")) == new Double(
                                                e2.getDouble("targetPercentage")) ? 0 : 1));
                    }
                };
                Collections.sort(objectList, sortOrder);

答案 15 :(得分:1)

在java`

中使用hashcode方法比较两个对象很容易
public class Sample{

  String a=null;
  String b=null;

  public Sample(){
      a="s";
      b="a";
  }
  public Sample(String a,String b){
      this.a=a;
      this.b=b;
  }
  public static void main(String args[]){
      Sample f=new Sample("b","12");
      Sample s=new Sample("b","12");
      //will return true
      System.out.println((s.a.hashCode()+s.b.hashCode())==(f.a.hashCode()+f.b.hashCode()));

      //will return false
      Sample f=new Sample("b","12");
      Sample s=new Sample("b","13");
      System.out.println((s.a.hashCode()+s.b.hashCode())==(f.a.hashCode()+f.b.hashCode()));

}

答案 16 :(得分:1)

迟到总比不到好 - 如果您正在寻找不必要的混乱或开销,那么在同时使用最少代码/快速执行方面很难击败以下各项。

数据类:

public class MyData {
    int id;
    boolean relevant;
    String name;
    float value;
}

比较器:

public class MultiFieldComparator implements Comparator<MyData> {
    @Override
    public int compare(MyData dataA, MyData dataB) {
        int result;
        if((result = Integer.compare(dataA.id, dataB.id)) == 0 &&
           (result = Boolean.compare(dataA.relevant, dataB.relevant)) == 0 &&
           (result = dataA.name.compareTo(dataB.name)) == 0)
            result = Float.compare(dataA.value, dataB.value);
        return result;
    }
}

如果您只是想按自定义顺序对集合进行排序,那么以下内容甚至更清晰:

myDataList.sort((dataA, dataB) -> {
    int result;
    if((result = Integer.compare(dataA.id, dataB.id)) == 0 &&
       (result = Boolean.compare(dataA.relevant, dataB.relevant)) == 0 &&
       (result = dataA.name.compareTo(dataB.name)) == 0)
        result = Float.compare(dataA.value, dataB.value);
    return result;
});

答案 17 :(得分:0)

如果您实施Comparable界面,则需要选择一个简单的属性来排序。这被称为自然排序。将其视为默认值。当没有提供特定的比较器时,它总是被使用。通常这是名称,但您的用例可能需要不同的东西。您可以自由使用任何数量的其他比较器,您可以提供给各种集合API以覆盖自然顺序。

另请注意,通常如果a.compareTo(b)== 0,则a.equals(b)== true。如果没有,这是好的,但有副作用需要注意。请参阅Comparable界面上的优秀javadoc,您将在此找到很多有用的信息。

答案 18 :(得分:0)

以下博客给出了良好的链式比较器示例

https://jsfiddle.net/hfy3dwf5/5/

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * This is a chained comparator that is used to sort a list by multiple
 * attributes by chaining a sequence of comparators of individual fields
 * together.
 *
 */
public class EmployeeChainedComparator implements Comparator<Employee> {

    private List<Comparator<Employee>> listComparators;

    @SafeVarargs
    public EmployeeChainedComparator(Comparator<Employee>... comparators) {
        this.listComparators = Arrays.asList(comparators);
    }

    @Override
    public int compare(Employee emp1, Employee emp2) {
        for (Comparator<Employee> comparator : listComparators) {
            int result = comparator.compare(emp1, emp2);
            if (result != 0) {
                return result;
            }
        }
        return 0;
    }
}

致电比较者:

Collections.sort(listEmployees, new EmployeeChainedComparator(
                new EmployeeJobTitleComparator(),
                new EmployeeAgeComparator(),
                new EmployeeSalaryComparator())
        );

答案 19 :(得分:0)

Steve's answer开始可以使用三元运算符:

public int compareTo(Person other) {
    int f = firstName.compareTo(other.firstName);
    int l = lastName.compareTo(other.lastName);
    return f != 0 ? f : l != 0 ? l : Integer.compare(age, other.age);
}

答案 20 :(得分:0)

//Following is the example in jdk 1.8
package com;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

class User {
    private String firstName;
    private String lastName;
    private Integer age;

    public Integer getAge() {
        return age;
    }

    public User setAge(Integer age) {
        this.age = age;
        return this;
    }

    public String getFirstName() {
        return firstName;
    }

    public User setFirstName(String firstName) {
        this.firstName = firstName;
        return this;
    }

    public String getLastName() {
        return lastName;
    }

    public User setLastName(String lastName) {
        this.lastName = lastName;
        return this;
    }

}

public class MultiFieldsComparision {

    public static void main(String[] args) {
        List<User> users = new ArrayList<User>();

        User u1 = new User().setFirstName("Pawan").setLastName("Singh").setAge(38);
        User u2 = new User().setFirstName("Pawan").setLastName("Payal").setAge(37);
        User u3 = new User().setFirstName("Anuj").setLastName("Kumar").setAge(60);
        User u4 = new User().setFirstName("Anuj").setLastName("Kumar").setAge(43);
        User u5 = new User().setFirstName("Pawan").setLastName("Chamoli").setAge(44);
        User u6 = new User().setFirstName("Pawan").setLastName("Singh").setAge(5);

        users.add(u1);
        users.add(u2);
        users.add(u3);
        users.add(u4);
        users.add(u5);
        users.add(u6);

        System.out.println("****** Before Sorting ******");

        users.forEach(user -> {
            System.out.println(user.getFirstName() + " , " + user.getLastName() + " , " + user.getAge());
        });

        System.out.println("****** Aftre Sorting ******");

        users.sort(
                Comparator.comparing(User::getFirstName).thenComparing(User::getLastName).thenComparing(User::getAge));

        users.forEach(user -> {
            System.out.println(user.getFirstName() + " , " + user.getLastName() + " , " + user.getAge());
        });

    }

}

答案 21 :(得分:0)

通常,每当我需要进行多级排序时,我都会像这样覆盖compareTo()方法。

public int compareTo(Song o) {
    // TODO Auto-generated method stub
    int comp1 = 10000000*(movie.compareTo(o.movie))+1000*(artist.compareTo(o.artist))+songLength;
    int comp2 = 10000000*(o.movie.compareTo(movie))+1000*(o.artist.compareTo(artist))+o.songLength;
    return comp1-comp2;
} 

这里首先是电影名称,然后是艺术家,最后是songLength。您只需要确保这些乘数相距足够远,就不会越过彼此的边界。

答案 22 :(得分:-1)

使用Google's Guava library很容易做到。

e.g。 Objects.equal(name, name2) && Objects.equal(age, age2) && ...

更多例子: