如何按多个字段比较对象 [英] How to compare objects by multiple fields
问题描述
假设您有一些对象,它们具有多个字段,可以通过以下方式进行比较:
Assume you have some objects which have several fields they can be compared by:
public class Person {
private String firstName;
private String lastName;
private String age;
/* Constructors */
/* Methods */
}
所以在这个例子中,当你问:
So in this example, when you ask if:
a.compareTo(b) > 0
您可能会问 a 的姓氏是否在 b 之前,或者 a 是否比 b 大,等等...
you might be asking if a's last name comes before b's, or if a is older than b, etc...
在不增加不必要的混乱或开销的情况下,在这些类型的对象之间启用多重比较的最简洁方法是什么?
What is the cleanest way to enable multiple comparison between these kinds of objects without adding unnecessary clutter or overhead?
java.lang.Comparable
接口只允许通过一个字段进行比较- 在我看来,添加大量比较方法(即
compareByFirstName()
、compareByAge()
等...)很混乱.
java.lang.Comparable
interface allows comparison by one field only- Adding numerous compare methods (i.e.
compareByFirstName()
,compareByAge()
, etc...) is cluttered in my opinion.
那么最好的方法是什么?
So what is the best way to go about this?
推荐答案
您可以实现一个 Comparator
来比较两个 Person
对象,并且您可以检查尽可能多的你喜欢的字段.您可以在比较器中放入一个变量,告诉它要与哪个字段进行比较,尽管编写多个比较器可能会更简单.
You can implement a Comparator
which compares two Person
objects, and you can examine as many of the fields as you like. You can put in a variable in your comparator that tells it which field to compare to, although it would probably be simpler to just write multiple comparators.
这篇关于如何按多个字段比较对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!