I have an iterator of strings.
For sorting i need to create a list from it and sort it using Collections.sort(list)
.
Is there any simple way to sort an iterator.
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 and for-each loop are faster than simple for loop for collections with no random access, while in collections which allows random access there is no performance change with for-each loop/for loop/iterator.
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.
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)
Actually you cannot,as Iterator is not an Collection.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With