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

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

问题描述

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

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.

实现这一目标的最简单方法是什么?

What is the easiest way to accomplish that?

我知道我可以实现 Comparable 接口,但这似乎限制了我按一个特定属性对其进行排序.

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

推荐答案

实施 比较器 接口(每个不同的排序顺序一次)并使用 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天全站免登陆