Sort an iterator of strings

后端 未结 3 1156
北海茫月
北海茫月 2021-01-12 17:10

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

相关标签:
3条回答
  • 2021-01-12 17:32

    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();
      }
    }
    
    0 讨论(0)
  • 2021-01-12 17:46

    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)

    0 讨论(0)
  • 2021-01-12 17:55

    Use TreeSet or TreeMap. They are collections that are already sorted.

    0 讨论(0)
提交回复
热议问题