java 从整数的可迭代对象中获取排序数组的最快方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13195787/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:50:16  来源:igfitidea点击:

Fastest way to get a sorted array out of an Iterable of integers

java

提问by Rajat Gupta

Possible Duplicate:
Fastest strategy to form and sort an array of positive integers

可能的重复:
形成和排序正整数数组的最快策略

What would be the fastest way to get a sorted array from an unsorted iterable of integers ? Currently I do it by iterating over the iterable n no of times (where n is size of list) each time getting the highest from iterable & putting it in array. But I'm looking to clean this up & let some good library do it for me.

从未排序的整数迭代中获取排序数组的最快方法是什么?目前,我通过迭代可迭代 n 次(其中 n 是列表的大小)来实现,每次从可迭代中获取最高值并将其放入数组中。但我正在寻找清理它并让一些好的图书馆为我做这件事。

Probably I won't mind using any popular libraries like Guava, etc for this purpose.

可能我不介意为此目的使用任何流行的库,例如 Guava 等。

采纳答案by assylias

As commented, the easiest and probably fastest way is to populate a collection and sort it - I would simply use an ArrayList in this case:

正如所评论的,最简单也可能是最快的方法是填充一个集合并对其进行排序 - 在这种情况下,我将简单地使用 ArrayList:

List<Integer> sortedList = new ArrayList<>();
for (Integer i : yourIterable) {
    sortedList.add(i);
}
Collections.sort(sortedList);

If you know the size of your Iterable beforehand you can initialise the arraylist with the right size to make an additional efficiency gain:

如果您事先知道 Iterable 的大小,您可以使用正确的大小初始化 arraylist 以提高效率:

List<Integer> sortedList = new ArrayList<>(size);

回答by Henrik Aasted S?rensen

It is essentially the same answer as assyliashas already provided, but if you have Google Guava on the classpath, you can shorten it to :

它与assylias已经提供的答案基本相同,但是如果类路径上有 Google Guava,则可以将其缩短为:

import java.util.Collections;
import java.util.List;

import com.google.common.collect.Lists;

...

List list = Lists.newArrayList(iterable);
Collections.sort(list);