【发布时间】:2015-02-23 03:41:57
【问题描述】:
我正在尝试使用 Lambda 表达式进行排序,但问题是我无法按正常顺序(例如 1、2、3、4)进行排序。我需要按另一个顺序排序(例如 2、1、3、4)。
有没有办法使用 Lambda 表达式来做到这一点?
这是我要转换为 Lambda 表达式的代码(如果可能):
private static Comparator<Card> bySuit = new Comparator<Card>() {
public int compare(Card c1, Card c2) {
int this_suit = c1.getSuit().value();
int other_suit = c2.getSuit().value();
if((this_suit == 2 && other_suit == 1) || (this_suit == 1 && other_suit == 2)){
return other_suit - this_suit;
}
return this_suit - other_suit;
}
};
编辑
发现我可以使用:
private static Comparator<Card> bySuit = (c1, c2) -> {
int this_suit = c1.getSuit().value();
int other_suit = c2.getSuit().value();
if((this_suit == 2 && other_suit == 1) || (this_suit == 1 && other_suit == 2)){
return other_suit - this_suit;
}
return this_suit - other_suit;
};
但是有更好的方法吗?
【问题讨论】:
-
那么,除了前两个元素之外,您想要自然顺序,还是只针对具有某些特定值的元素?例如,应该是什么结果或排序
3,4,5,6? -
@pshemo 仅对某些具有特定值的元素。
标签: java sorting lambda compare