【发布时间】: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 完成吗:可以,但是需要自己写。你有没有尝试过?