Java 对字符串的迭代器进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16434526/
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 an iterator of strings
提问by sp_user123
I have an iterator of strings.
我有一个字符串迭代器。
For sorting i need to create a list from it and sort it using Collections.sort(list)
.
为了排序,我需要从中创建一个列表并使用Collections.sort(list)
.
Is there any simple way to sort an iterator.
有没有简单的方法来对迭代器进行排序。
采纳答案by mschenk74
An Iterator is NOT a container, it is a utility for traversing over the elements of a container. So if you only have access to the Iterator there is no way to change the order of iteration which is defined by the creator of this iterator.
Iterator 不是容器,它是用于遍历容器元素的实用程序。因此,如果您只能访问迭代器,则无法更改此迭代器的创建者定义的迭代顺序。
If you can't change the original container, you'll have to gather the elements delivered by the iterator within a new Collection and sort them therein.
如果您无法更改原始容器,则必须将迭代器提供的元素收集到一个新集合中,并在其中对它们进行排序。
(A good approach to understand what is possible with iterators is to have a look at the Source-code of the JDK classes or to implement an own iterator)
(了解迭代器的可能性的一个好方法是查看 JDK 类的源代码或实现自己的迭代器)
回答by Suresh Atta
Actually you cannot,as Iterator is not an Collection.
实际上你不能,因为 Iterator 不是一个集合。
If it is obvious,you can do
如果很明显,你可以做
public static Iterator sortedIterator(Iterator it, Comparator comparator) {
List list = new ArrayList();
while (it.hasNext()) {
list.add(it.next());
}
Collections.sort(list, comparator);
return list.iterator();
}
}
回答by renz
Use TreeSet or TreeMap. They are collections that are already sorted.
使用 TreeSet 或 TreeMap。它们是已经排序的集合。