Sort an iterator of strings

后端 未结 3 1179
北海茫月
北海茫月 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条回答
  •  梦毁少年i
    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();
      }
    }
    

提交回复
热议问题