/** * Map a set: generate a new set with each element mapped. The new set is always a {@link * HashSet}; it would have been more precise to use {@link java.lang.reflect reflection} to create * a set of the same type as 'srcSet', but reflection works really slowly in some implementations, * so it's best to avoid it. * * @throws IllegalArgumentException if srcSet == null */ public static <T, U> Set<U> mapToSet(Collection<T> srcSet, Function<T, U> f) throws IllegalArgumentException { if (srcSet == null) { throw new IllegalArgumentException("srcSet == null"); } HashSet<U> result = HashSetFactory.make(); for (Iterator<T> srcIter = srcSet.iterator(); srcIter.hasNext(); ) { result.add(f.apply(srcIter.next())); } return result; }
@SuppressWarnings("unchecked") public static <S, T> Set<T> filterByType(Iterable<S> c, Class<T> klass) { Set<T> result = HashSetFactory.make(); for (S s : c) if (klass.isAssignableFrom(s.getClass())) result.add((T) s); return result; }