Java tutorial
//package com.java2s; //License from project: LGPL import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.function.Supplier; import java.util.stream.Collector; import java.util.stream.Collectors; public class Main { /** * Transforms the given iterator to list * * @param <T> * the generic type * @param iterator * the iterator * @return the list */ public static <T> List<T> toList(Iterator<T> iterator) { return toCollection(iterator, ArrayList::new); } /** * Returns a {@code Collector} that accumulates the input elements into a new {@code List}, in encounter order. If * the provided size is greater than zero then {@link ArrayList} with the given size will be created otherwise a * {@link LinkedList} will be created for undermined size. * * @param <T> * the type of the input elements * @param <C> * the type of the resulting {@code Collection} * @param expectedSize * the expected size of the collection if known. If not known a -1 could be passed. * @return a {@code Collector} which collects all the input elements into a {@code List}, in encounter order */ @SuppressWarnings("unchecked") public static <T, C extends Collection<T>> Collector<T, ?, C> toList(int expectedSize) { if (expectedSize > 0) { return (Collector<T, ?, C>) Collectors.toCollection(() -> new ArrayList<>(expectedSize)); } return (Collector<T, ?, C>) Collectors.toCollection(LinkedList::new); } /** * Converts the given iterator to collection created via the provided {@link Supplier}. * <p> * Example use: <code>List<String> list = CollectionUtils.toCollection(iterator, LinkedList::new);</code> * * @param <T> * the generic type * @param <C> * the generic type * @param iterator * the iterator * @param newInstance * the new instance * @return the c */ public static <T, C extends Collection<T>> C toCollection(Iterator<T> iterator, Supplier<C> newInstance) { Objects.requireNonNull(iterator, "The iterator is required"); Objects.requireNonNull(newInstance, "New Instance supplier is required"); C list = newInstance.get(); iterator.forEachRemaining(list::add); return list; } }