对集合进行排序
我有一个 Persons 对象列表,有两个属性名称和年龄。我想按年龄升序对这个列表进行排序,排序应该是所有名字相同的人都应该在列表的底部。
I have a list of Persons object having two attributes name and age. I want to sort this list by age in ascending order, the sorting should be such that all the persons whose names are same should be at the bottom of the list.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在您的
Person
类中实现Compareable
接口(我并没有真正遵循您的逻辑,但我认为您可以将compareTo
方法更改为您需要的方法):输出:
Implement
Compareable
interface in yourPerson
class (I don't really follow your logic but I think you can change thecompareTo
method into something you need):Output:
看一下 Collections.sort 以便根据元素的自然顺序对列表进行排序。列表中的所有元素(即您的情况下的 Person 对象)应实现 类似界面。
Take a look at Collections.sort in order to sort a list according to the natural ordering of its elements. All elements in the list (i.e. Person objects in your case) should implement the Comparable interface.
使用
Comparator
而不是使用Comparable
。Comparator
接口使您能够以任意数量的不同方式对给定集合进行排序。关于 Comparator 接口的另一个方便的事情是,您可以使用它对任何类的实例进行排序 - 甚至您无法修改的类,这与
Comparable
接口不同,后者强制您更改要对其实例进行排序的类。Instead of using
Comparable
useComparator
. TheComparator
interface gives you the capability to sort a given collection any number of different ways. The other handy thing about theComparator
interface is that you can use it to sort instances of any class—evenclasses you can't modify—unlike the
Comparable
interface, which forces you to change the class whose instances you want to sort.哦,我的蜘蛛感应很刺痛,让我怀疑是作业:)我只会给你基本的想法。
您可以使用常规比较器对列表进行排序,然后使用另一个循环根据名称对名称进行分组。
使用 lambdaJ 我会这样做:
输出:
Ooh, my spider-sense is tingling and makes me suspect a homework assignment :) I'll merely give you the basic idea.
You could sort the list with a regular comparator and then group the names according to the name with another loop.
With lambdaJ I would do it like this:
Output: