对对象的集合进行排序 [英] Sorting a collection of objects

查看:93
本文介绍了对对象的集合进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个简单的字符串列表:

If I have a simple list of Strings:

List<String> stringList = new ArrayList<String>();

我可以使用:

Collections.sort(stringList);

但是假设我有一个Person类:

But suppose I have a Person class:

public class Person
{
   private String name;
   private Integer age;
   private String country;
}

其列表:

List<Person> personList = new ArrayList<Person>();

我想根据名字,有时是按年龄,有时是按国家排序。

And I want to sort it sometimes by name, sometimes by age, sometimes by country.

最简单的方法是什么?

我知道我可以实现Comparable接口,限制我通过一个特定的属性来排序。

I know that I can implement the Comparable interface, but that seems to limit me to sort it by one specific property.

推荐答案

实现 Comparator 界面(每个不同排序顺序一次),并使用 Collections.sort( )方法,它将Comparator作为附加参数。

Implement the Comparator interface (once for each different sort order) and use the Collections.sort() method that takes a Comparator as additional parameter.

这篇关于对对象的集合进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆