【问题标题】:Lambda Expressions for Comparing/sorting limited values in fixed, non-natural order用于以固定、非自然顺序比较/排序有限值的 Lambda 表达式
【发布时间】: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


【解决方案1】:

这与 lambda 表达式无关:如果您想要按固定顺序排序/比较的项目数量有限,您可以将该顺序写入数组中,然后比较数组中的值:

int[] myOrder = {2, 1, 3, 4};
Comparator<Card> bySuit = (c1, c2) -> Integer.compare(
    myOrder[c1.getSuit().value() - 1], myOrder[c2.getSuit().value() - 1]);

如果您要排序的值不是(几乎)完整的范围,您可以使用Map&lt;Key, Integer&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-21
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多