繁体   English   中英

用一种方式对列表中的某些项目进行排序,而另一种方式进行排序的最佳方法是什么?

[英]What's the best way to sort some items in a list in one way, and the rest, another way?

说我进行搜索,该搜索返回对象列表

{ 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

最好进行排序(最好不创建临时列表)的最佳方法是什么?

可以使用一个比较器还是使用流来完成?

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

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

不确定您的班级是什么样子-是您要的吗?

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

您可以使用一个凌乱的比较器来实现。 这个想法是:

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有点生锈。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM