如何按某些属性对对象列表进行排序
我有简单的类
public class ActiveAlarm {
public long timeStarted;
public long timeEnded;
private String name = "";
private String description = "";
private String event;
private boolean live = false;
}
和 List
con。如何按 timeStarted
升序排序,然后按 timeEnded
升序排序?有人可以帮忙吗?我知道 C++ 中有通用算法和重载运算符 <,但我对 Java 很陌生。
I have simple class
public class ActiveAlarm {
public long timeStarted;
public long timeEnded;
private String name = "";
private String description = "";
private String event;
private boolean live = false;
}
and List<ActiveAlarm>
con. How to sort in ascending order by timeStarted
, then by timeEnded
? Can anybody help? I know in C++ with generic algorithm and overload operator <, but I am new to Java.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(18)
使用
比较器
例如:
从 Java 8 开始,您可以简单地使用 lambda 表达式来表示 Comparator 实例。
Using
Comparator
For Example:
With Java 8 onwards, you can simply use lambda expression to represent Comparator instance.
使
ActiveAlarm
实现Comparable
或在单独的类中实现Comparator
。然后调用:或者
一般来说,实现 是个好主意
Comparable
如果有一个“自然”排序顺序...否则(如果您碰巧想要按特定顺序排序,但可能同样容易想要一个不同的)最好实现Comparator
。老实说,这种特殊情况可能会发生任何一种情况......但我可能坚持使用更灵活的
Comparator
选项。编辑:示例实现:
Either make
ActiveAlarm
implementComparable<ActiveAlarm>
or implementComparator<ActiveAlarm>
in a separate class. Then call:or
In general, it's a good idea to implement
Comparable<T>
if there's a single "natural" sort order... otherwise (if you happen to want to sort in a particular order, but might equally easily want a different one) it's better to implementComparator<T>
. This particular situation could go either way, to be honest... but I'd probably stick with the more flexibleComparator<T>
option.EDIT: Sample implementation:
JAVA 8 及以上答案(使用 Lambda 表达式)
在 Java 8 中,引入了 Lambda 表达式,使这变得更加容易!您可以将其简化如下:(使用您的对象作为示例)
甚至更短:
该语句相当于以下内容:
将 Lambda 表达式视为仅需要您放入代码的相关部分:方法签名和返回的内容。
您问题的另一部分是如何与多个字段进行比较。要使用 Lambda 表达式执行此操作,您可以使用
.thenComparing()
函数有效地将两个比较合并为一个:上面的代码将首先按
timeStarted
对列表进行排序,然后然后按timeEnded
(对于那些具有相同timeStarted
的记录)。最后一点:比较“long”或“int”基元很容易,您只需将其中一个减去另一个即可。如果您正在比较对象(“Long”或“String”),我建议您使用它们的内置比较。示例:
编辑:感谢 Lukas Eder 将我指向
.thenComparing()
函数。JAVA 8 and Above Answer (Using Lambda Expressions)
In Java 8, Lambda expressions were introduced to make this even easier! Instead of creating a Comparator() object with all of it's scaffolding, you can simplify it as follows: (Using your object as an example)
or even shorter:
That one statement is equivalent to the following:
Think of Lambda expressions as only requiring you to put in the relevant parts of the code: the method signature and what gets returned.
Another part of your question was how to compare against multiple fields. To do that with Lambda expressions, you can use the
.thenComparing()
function to effectively combine two comparisons into one:The above code will sort the list first by
timeStarted
, and then bytimeEnded
(for those records that have the sametimeStarted
).One last note: It is easy to compare 'long' or 'int' primitives, you can just subtract one from the other. If you are comparing objects ('Long' or 'String'), I suggest you use their built-in comparison. Example:
EDIT: Thanks to Lukas Eder for pointing me to
.thenComparing()
function.我们可以通过以下两种方式之一对列表进行排序:
1.使用Comparator:当需要在多个地方使用排序逻辑时
如果您想在单个位置使用排序逻辑,那么您可以编写一个匿名内部类,如下所示,或者提取比较器并在多个位置使用它
如果我们可以使用 '长”而不是“长”。
2.使用 Comparable(自然排序):如果排序算法始终坚持一个属性:
编写一个实现“Comparable”的类并重写“compareTo”方法,如下定义
}
调用排序方法根据自然顺序进行排序
We can sort the list in one of two ways:
1. Using Comparator : When required to use the sort logic in multiple places
If you want to use the sorting logic in a single place, then you can write an anonymous inner class as follows, or else extract the comparator and use it in multiple places
We can have null check for the properties, if we could have used 'Long' instead of 'long'.
2. Using Comparable(natural ordering): If sort algorithm always stick to one property:
write a class that implements 'Comparable' and override 'compareTo' method as defined below
}
call sort method to sort based on natural ordering
在java8+中,这可以单行编写,如下所示:
collectionObjec.sort(comparator_lamda)
或comparator.comparing(CollectionType::getterOfProperty)
代码:
或
In java8+ this can be written in single line as follows:
collectionObjec.sort(comparator_lamda)
orcomparator.comparing(CollectionType::getterOfProperty)
code:
or
这应该会给你一个粗略的想法。完成后,您可以在列表上调用
Collections.sort()
。That should give you a rough idea. Once that's done, you can call
Collections.sort()
on the list.从 Java8 开始,使用 < 的组合可以更干净地完成此操作code>Comparator 和
Lambda 表达式
例如:
Since Java8 this can be done even cleaner using a combination of
Comparator
andLambda expressions
For Example:
使用 Stream API< 的 Java-8 解决方案/a>:
A. 当
timeStarted
和timeEnded
为public
时(如要求中所述),因此执行不(需要)有public
getter 方法:B. 当
timeStarted
和timeEnded
有public
getter 方法时:如果您想对原始
列表
本身进行排序:A.当
timeStarted
和timeEnded
是public< /code> (如要求中所述),因此不需要(需要)具有
public
getter 方法:B. 当
timeStarted
和timeEnded
具有public
时获取方法:Java-8 solution using Stream API:
A. When
timeStarted
andtimeEnded
arepublic
(as mentioned in the requirement) and therefore do not (need to) havepublic
getter methods:B. When
timeStarted
andtimeEnded
havepublic
getter methods:If you want to sort the original
list
itself:A. When
timeStarted
andtimeEnded
arepublic
(as mentioned in the requirement) and therefore do not (need to) havepublic
getter methods:B. When
timeStarted
andtimeEnded
havepublic
getter methods:Guava 的比较链:
Guava's ComparisonChain:
这就是对我有用的东西。
比我发现的其他内容更短、更容易:
最后的“.reversed()”部分是我的特定项目的要求,但我也分享它,因为花了一段时间才找到它
Here's what did the trick for me.
Was much shorter and easier than everything else I found:
The ".reversed()" part at the end was a requirement for my specific project but I'm sharing it too, as it took a while to find it
我们可以使用 Comparator.comparing() 方法根据对象的属性对列表进行排序。
请注意,在执行此操作之前,您必须至少定义要作为排序基础的属性的 getter 方法。
输出:
We can use the
Comparator.comparing()
method to sort a list based on an object's property.Note that before doing it, you'll have to define at least the getter methods of the properties you want to base your sort on.
Output:
员工POJO类
员工类来管理员工
自定义排序
Employee POJO Class
Employee Class To Manage Employee
Custom Sorting
您可以使用
Collections.sort
并传递您自己的Comparator
You can use
Collections.sort
and pass your ownComparator<ActiveAlarm>
在java中,您需要使用静态
Collections.sort
方法。下面是 CompanyRole 对象列表的示例,首先按开始排序,然后按结束排序。您可以轻松适应自己的对象。In java you need to use the static
Collections.sort
method. Here is an example for a list of CompanyRole objects, sorted first by begin and then by end. You can easily adapt for your own object.您可以调用 Collections.sort() 并传入一个比较器,您需要编写该比较器来比较对象的不同属性。
You can call Collections.sort() and pass in a Comparator which you need to write to compare different properties of the object.
如前所述,您可以通过以下方式进行排序:
Comparable
Comparator
传递给Collections.sort
如果您同时执行这两个操作,则
Comparable
将被忽略,而Comparator
将被使用。这有助于值对象拥有自己的逻辑Comparable
,这对于您的值对象来说是最合理的排序,而每个单独的用例都有自己的实现。As mentioned you can sort by:
Comparable
Comparator
toCollections.sort
If you do both, the
Comparable
will be ignored andComparator
will be used. This helps that the value objects has their own logicalComparable
which is most reasonable sort for your value object, while each individual use case has its own implementation.在 Java(Java 8 及更高版本)中对任何对象列表进行排序的最佳且最简单的方法。
让我们根据属性“fruitName”对一篮子水果进行排序
Fruit POJO:
现在让我们将水果添加到列表中,然后对其进行排序
您现在可以打印列表(即basketOfFruits),并且列表中的水果将按升序排序(按字典顺序)。
输出如下所示:
也可以使用 Java 流(Java 8 及更高版本)代替 Collections.sort()。以下是使用 Java 流的代码
,其中列表以与 Collections.sort() 相同的方式排序,但排序后的项目将存储/收集在另一个列表“sortedFruits”中。因此,如果我们想打印列表中已排序的项目,则在本例中需要打印“sortedFruits”而不是“basketOfFruits”
The best and the easiest way to sort any list of objects in Java (Java 8 and above).
Lets sort a basket of fruits based on the property "fruitName"
Fruit POJO:
Now lets add fruits into a list and then sort it
You can now print the list (i.e basketOfFruits) and the fruits in the list would be sorted in ASCENDING order (lexicographically).
The output would look like this:
Instead of Collections.sort(), Java streams can also be used (Java 8 and above). The following is the code using Java streams
here the list is sorted in the same manner as Collections.sort(), but the sorted items would be stored/collected in another list "sortedFruits". So, if we want to print the sorted items of the list, we need to print "sortedFruits" instead of "basketOfFruits" in this case