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 t
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();
}
}
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)
Use TreeSet or TreeMap. They are collections that are already sorted.