使用比较器在 Java 中对集合进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25015400/
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
Sort set in java using Comparator
提问by user3887681
I am trying to sort set using Comparator
as shown below.
我正在尝试使用Comparator
如下所示对集合进行排序。
Set seatSet = tc.getTheatreSeat();
List listArr = new ArrayList(seatSet);
Collections.sort(listArr, new Comparator() {
public int compare(Object arg0, Object arg1) {
TheatreSeat r1 = (TheatreSeat) arg0;
TheatreSeat r2 = (TheatreSeat) arg1;
if (r2.getId() < r1.getId()) {
return 1;
}
return 0;
}
});
But its not working. whats wrong with my code please help.
但它不工作。我的代码有什么问题请帮忙。
回答by soru
The return value for a compare function should be -1, 0 or +1, not just 1 or 0.
比较函数的返回值应该是 -1、0 或 +1,而不仅仅是 1 或 0。
return Integer.compare(r1.getId(), r2.getId());
in place of the if statement should do the job.
代替 if 语句应该可以完成这项工作。
A Java 8 sort using a lambda would be
使用 lambda 的 Java 8 排序将是
listArr.sort(Comparator.comparing(e -> e.getId()));
回答by Rene M.
It looks correct enough that it should work mostly.
它看起来足够正确,它应该主要工作。
For understanding the int return value of a comparator defines 3 results:
为了理解比较器的 int 返回值定义了 3 个结果:
- less then 0 (minus values) means first element is behind second
- zero means they are equals
- more then 0 (positiv values) means first element is before second
- 小于 0(负值)意味着第一个元素在第二个之后
- 零表示它们相等
- 大于 0(正值)表示第一个元素在第二个元素之前
By inversing positive to negative and vice versa you can define ascending and descending order.
通过将正负反转,反之亦然,您可以定义升序和降序。
So here a full version of your comparator (I placed the IDs in variables to make it more simple to read):
所以这里有一个完整版本的比较器(我将 ID 放在变量中以使其更易于阅读):
new Comparator() {
public int compare(Object val1, Object val2) {
int id1 = ((TheatreSeat) val1).getId();
int id2 = ((TheatreSeat) val2).getId();
return id1 - id2;
}
}
So why I write id1 - id2 ? Because it results in exactly what we want. If id2 is greater then id1 the result will be less zero and vice versa and when id1 and id2 equals the result will be zero ;)
那我为什么要写 id1 - id2 呢?因为它的结果正是我们想要的。如果 id2 大于 id1,则结果将小于零,反之亦然,当 id1 和 id2 相等时,结果将为零;)
Use a step debugger to inspect your List before sorting and after to check the result.
在排序之前和之后使用步进调试器检查您的列表以检查结果。