java 按字母顺序对复杂对象的数组列表进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13380908/
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
sort arraylist of complex objects alphabetically
提问by CQM
I know that Collections.sort(myArrayList)
can sort an arraylist alphabetically when they are strings, but what about when they are something more complex such as a data object containing two or more variables including a String
. Is there a way to sort them then?
我知道Collections.sort(myArrayList)
当它们是字符串时可以按字母顺序对数组列表进行排序,但是当它们是更复杂的东西时,例如包含两个或多个变量(包括String
. 那么有没有办法对它们进行排序?
If there isn't a way with Collections
then I can imagine making a for loop or standard sorting algorithm to look at the strings variable of each object and move the object's index in the array.
如果没有办法,Collections
那么我可以想象制作一个 for 循环或标准排序算法来查看每个对象的字符串变量并在数组中移动对象的索引。
But I was wondering mainly if I overlooked something about the Collections
methods
但我主要想知道我是否忽略了有关Collections
方法的某些内容
回答by Denys Séguret
Use the function taking as second parameter a Comparator.
Il allows you to pass an instance of Comparator to sort according to your needs. Note that the javadoc of Comparatorcontains guidelines regarding the building of comparators.
Il 允许您传递 Comparator 的实例以根据您的需要进行排序。请注意Comparator的javadoc包含有关构建比较器的指南。
You may define the comparator as an anonymous class if it's only locally used. Here's an example where I sort objects regarding to one of their fields which is a String :
如果仅在本地使用,您可以将比较器定义为匿名类。这是一个示例,我对对象的其中一个字段进行排序,该字段是 String :
Collections.sort(groupResults, new Comparator<ProductSearchResult>() {
public int compare(ProductSearchResult result1, ProductSearchResult result2) {
return result1.product.getRsId().compareTo(result2.product.getRsId());
}
});
Alternatively, you might also make your class implement the Comparableinterface but this makes sense only if you can define a natural (obvious) order.
或者,您也可以让您的类实现Comparable接口,但这只有在您可以定义自然(明显)顺序时才有意义。
回答by dstronczak
I would create an inner class implementing the Comparator interface:
我将创建一个实现 Comparator 接口的内部类:
public class Car {
public double horsePower;
class CarHorsePowerComparator implements Comparator<Car> {
@Override
public int compare(Car car1, Car car2) {
return Integer.valueOf(car.horsePower).compareTo(Integer.valueOf(car2.horsePower)) }
}
}
Now when you want to sort your Car list by horsePower:
现在,当您想按马力对汽车列表进行排序时:
List<Car> list = new ArrayList<Car>(myCars); //your Car list
Collections.sort(list, new CarHorsePowerComparator());