Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an iterator of strings

Tags:

java

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.

like image 899
sp_user123 Avatar asked May 08 '13 06:05

sp_user123


People also ask

Can you 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.

Which is faster for loop or 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.


2 Answers

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)

like image 71
mschenk74 Avatar answered Nov 06 '22 08:11

mschenk74


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();
  }
}
like image 38
Suresh Atta Avatar answered Nov 06 '22 08:11

Suresh Atta