Java examples for java.util:Iterator
Get the max value from Iterator and Comparable
//package com.book2s; import java.util.ArrayList; import java.util.Comparator; import java.util.Iterator; import java.util.List; public class Main { public static void main(String[] argv) { Iterator iterator = java.util.Arrays.asList("asdf", "book2s.com") .iterator();/*w ww . ja va2 s .c o m*/ System.out.println(max(iterator)); } public static <T extends Comparable<? super T>> T max( Iterator<? extends T> iterator) { T next, candidate = iterator.next(); while (iterator.hasNext()) { if ((next = iterator.next()).compareTo(candidate) > 0) { candidate = next; } } return candidate; } public static <T> T max(Iterator<? extends T> iterator, Comparator<T> comparator) { T next, candidate = iterator.next(); while (iterator.hasNext()) { if (comparator.compare(next = iterator.next(), candidate) > 0) { candidate = next; } } return candidate; } public static <E> List<E> asList( @SuppressWarnings("unchecked") final E... array) { List<E> list = new ArrayList<>(array.length); for (E element : array) { list.add(element); } return list; } public static <E> List<E> asList(final Iterator<? extends E> iterator) { List<E> list = new ArrayList<>(); while (iterator.hasNext()) { list.add(iterator.next()); } return list; } }