【问题标题】:What's the best way to sort some items in a list in one way, and the rest, another way?以一种方式对列表中的某些项目进行排序的最佳方法是什么,而其余的则以另一种方式排序?
【发布时间】:2017-03-28 18:29:07
【问题描述】:

假设我进行了一个返回对象列表的搜索

{ age: 5, color: Yellow, eggs: 2 }
{ age: 3, color: White,  eggs: 5 }
{ age: 4, color: Brown,  eggs: 9 }
{ age: 2, color: Green,  eggs: 4 }
{ age: 3, color: Red,    eggs: 1 }
{ age: 1, color: Blue,   eggs: 6 }

我想将它们全部输出,但要按特定顺序。 如果年龄是 3 岁,我首先要这些物品,按最多的鸡蛋排序。 然后我希望其余项目按颜色按字母顺序排序。

所以排序后的列表将是

|   3's: eggs   |    rest: alphabetically on color    |
 White  -  Red  -  Blue  -  Brown  -  Green  -  Yellow

进行这种排序的最佳方法是什么,最好不要创建临时列表?

是否可以使用单个 Comparator 或使用流来完成?

【问题讨论】:

  • 如果你认为这是元素的自然顺序,我会让类实现 Comparable 接口 ant 正确实现 compareTo() 方法
  • 可以用一个 Comparator 完成吗:可以,但是需要自己写。你有没有尝试过?

标签: java sorting


【解决方案1】:

你可以用一个单一的、有点凌乱的比较器来做到这一点。这个想法是:

int compare(myType obj1, myType obj2)
{
    // first compare age
    if (obj1.age == 3)
    {
        if (obj2.age == 3)
        {
            // ages are both 3, so count eggs
            return obj1.eggs.compareTo(obj2.eggs);
        }
        // age 3 sorts before everything else
        return -1;
    }
    else if (obj2.age == 3)
    {
        // if obj2.age is 3, and obj1.age isn't 3,
        // then obj1 is greater than obj2
        return 1;
    }

    // compare color
    return obj1.color.compareTo(obj2.color);
}

请原谅任何语法错误;我的 Java 有点生疏了。

【讨论】:

    【解决方案2】:

    从 Java 8 开始,Comparator 有了一些有用的静态方法:

    new AgeComparator().thenComparingInt(MyObj::getEggs).thenComparing(new ColorComparator());
    

    不确定你的班级是什么样的 - 是你要求的吗?

    总的来说,我也喜欢 Apache Commons 的 CompareToBuilder 用于合并比较,但在你的情况下,它似乎太有限了。

    【讨论】:

    • 我认为这不会达到他想要的效果。这将按年龄排序,在同一年龄内,它将按鸡蛋的数量排序,然后按颜色排序。因此,使用您的建议的输出会将年龄 1 和 2 的项目放在 3 之前。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-08
    • 2012-04-12
    • 2017-03-06
    • 2018-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多