[英]How can I sort an ArrayList faster?
I'm doing a class project and I need to sort ArrayLists of custom objects based on the values of their int attributes. 我正在做一个类项目,我需要根据其int属性的值对自定义对象的ArrayList进行排序。
I'm currenly using something like this: 我正在使用类似这样的内容:
public static void Sort(ArrayList <MyObject> objectList){
for (int i = 0; i < list.size()-1; i++){
for (int j = 0; j < list.size()-1; j++){
if (objectList.get(j).getA() > objectList.get(j+1).getA()){
Collections.swap(objectList, j, j+1);
}
}
}
}
The program works well if the ArrayList has less than 10^4 elements. 如果ArrayList的元素少于10 ^ 4,则程序运行良好。 But if I try to sort 10^5 elements it takes several minutes, and I need to sort 10^6 elements.
但是,如果我尝试对10 ^ 5个元素进行排序,则需要花费几分钟,因此我需要对10 ^ 6个元素进行排序。 Any suggestions?
有什么建议么?
Use the List::sort
method: 使用
List::sort
方法:
objectList.sort(Comparator.comparing(MyObject::getA));
As @lexicore has mentioned below, it seems like getA()
returns a numeric type, in which case if it returns int
then it's better to use comparingInt
instead of comparing
above, if it's long
use comparingLong
or if it's a float
/ double
then use comparingDouble
for better performance. 如@lexicore已经如下所述,它看起来像
getA()
返回一个数字型,如果它返回在这种情况下int
那么它最好使用comparingInt
代替comparing
以上,如果是long
使用comparingLong
或者如果它是一个float
/ double
然后使用comparingDouble
以获得更好的性能。
Currently, your implementation is O(n^2)
which means that as the array grows, the time will expand quadratically. 当前,您的实现是
O(n^2)
,这意味着随着数组的增长,时间将平方增长。
Without going into a lot of details of using mergesort which is O(log(n) xn)
, the fastest way is to use Java's built-in solution for sorting. 无需讨论使用
O(log(n) xn)
mergesort的许多细节,最快的方法是使用Java的内置解决方案进行排序。
Collections.sort(list);
Link to API . 链接到API 。 There is also
Collection.sort(list, comparator)
which allows you to provide your own comparator . 还有
Collection.sort(list, comparator)
,它允许您提供自己的比较器 。
Do you want it to be even faster? 您是否希望它更快? You can use the Java's new feature which allows you to sort with multiple cores in parallel.
您可以使用Java的新功能 ,该功能允许您并行处理多个内核。 Here is the API .
这是API 。 Notice that
Arrays.sort()
and Arrays.parallelSort()
take an array as the first parameter. 请注意,
Arrays.sort()
和Arrays.parallelSort()
将数组作为第一个参数。 You will need to convert a list to an array using list.toArray()
. 您将需要使用
list.toArray()
将列表转换为数组。
Finally, do note that List#sort()
was introduced only in Java 8. 最后,请注意
List#sort()
仅在Java 8中引入 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.