java 按对象属性对对象的 ArrayList 进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3342517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sorting ArrayList of Objects by Object attribute
提问by Vishal
I am having an Arraylist of Objects. Those object have an attribute or datatype - 'String'. I need to sort the Arraylist by that string. How to achieve this?
我有一个对象的 Arraylist。这些对象有一个属性或数据类型 - 'String'。我需要按该字符串对 Arraylist 进行排序。如何实现这一目标?
回答by polygenelubricants
You need to write a Comparator<MyObject>and use Collections.sort(List<T>, Comparator<? super T>to sort your List.
您需要编写一个Comparator<MyObject>并用于Collections.sort(List<T>, Comparator<? super T>对您的List.
Or else, your MyObjectcan also implements Comparable<MyObject>, defining a natural orderingthat compares on your specific attribute, and then use Collections.sort(List<T>instead.
否则,您MyObject也可以implements Comparable<MyObject>,定义一个自然排序来比较您的特定属性,然后使用Collections.sort(List<T>。
See also
也可以看看
Related questions
相关问题
On sorting Liston various criteria:
List根据各种标准进行排序:
On Comparatorand Comparable
在Comparator和Comparable
回答by ColinD
Another good way of doing this that is a bit more flexible if there is more than one property of an object that you may wish to sort by is to use Guava's Orderingclass with its onResultOf(Function)option. This is ideally suited for sorting by properties since a Functioncan be used to retrieve and return a specific property of an object.
For a simple example, imagine a class Personwith String getFirstName()and String getLastName()methods.
如果您可能希望排序的对象有多个属性,另一种更灵活的好方法是使用Guava的Ordering类及其onResultOf(Function)选项。这非常适合按属性排序,因为函数可用于检索和返回对象的特定属性。举一个简单的例子,想象一个Person带有String getFirstName()和String getLastName()方法的类。
List<Person> people = ...;
Collections.sort(people, Ordering.natural().onResultOf(
new Function<Person, String>() {
public String apply(Person from) {
return from.getFirstName();
}
}));
The above will sort the list by first name.
以上将按名字对列表进行排序。
To make it read nicer, you may want to define the functions you might want to use as public static finalfields on the Personclass. Then you could sort by last name like this:
为了使它更好读,您可能需要定义您可能希望用作类中public static final字段的函数Person。然后你可以像这样按姓氏排序:
Collections.sort(people, Ordering.natural().onResultOf(Person.GET_LAST_NAME));
As a fun aside note, this will all be a lot easier in Java 8 with lambda expressions and method references. You'll be able to write something like this without having to define any clumsy anonymous inner classes or static final fields:
作为一个有趣的旁注,这在 Java 8 中使用 lambda 表达式和方法引用会容易得多。您将能够编写这样的东西,而无需定义任何笨拙的匿名内部类或静态最终字段:
import static java.util.Comparator.comparing;
...
people.sort(comparing(Person::getLastName));

