Java tutorial
//package com.java2s; //License from project: LGPL import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Objects; import java.util.Set; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; public class Main { /** * The size increase of the created sets and maps to compensate the not full load factor of the maps and sets. */ private static final float SIZE_NORMALIZATION = 1.1f; /** The load factor for maps and sets. */ private static final float LOAD_FACTOR = 0.95f; /** * Transform the source collection using the mapping function to convert the elements to the output type. The result * is written to a set. * * @param <T> * the source type type * @param <R> * the result type * @param source * the source * @param mapping * the mapping used for the value transformation * @return the sets the */ public static <T, R> Set<R> transformToSet(Collection<T> source, Function<T, R> mapping) { return source.stream().map(mapping) .collect(Collectors.toCollection(() -> createLinkedHashSet(source.size()))); } /** * 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; } /** * Creates the linked hash set instance that will hold the given amount of elements. The returned instance is * optimized for that size and will not grow until the given number of elements are added. * <p> * The method is same as <code>new LinkedHashSet<V>((int) (size * 1.1), 0.95f)</code> * * @param <V> * the value type * @param size * the preferred size * @return the map instance */ public static <V> Set<V> createLinkedHashSet(int size) { return new LinkedHashSet<>((int) (size * SIZE_NORMALIZATION), LOAD_FACTOR); } }