Java tutorial
//package com.java2s; //License from project: LGPL import java.util.Collection; import java.util.LinkedHashSet; import java.util.Set; public class Main { /** * Appends value to collection. If value is collection all elements are added, if value is object it is simply * added. If skipDuplicates is set to true, objects already contained in the collection are not added again. Note * that element would be type casted to collection type. * * @param data * is the collection to update - set, list, etc. Should be modifiable * @param value * is value of type T or {@link Collection} of elements of type T * @param skipDuplicates * whether to treat data as {@link Set}. Note if data is already {@link Set} parameter does not affect * the result. Note if data already contains duplicate elements they are not affected. * @return the updated data collection */ @SuppressWarnings("unchecked") public static <T> Collection<T> addValue(Collection<T> data, Object value, boolean skipDuplicates) { if (value instanceof Collection) { Collection<T> toBeAdded = (Collection<T>) value; if (skipDuplicates && !(data instanceof Set)) { Set<T> nonDuplicates = new LinkedHashSet<>(toBeAdded); nonDuplicates.removeAll(data); data.addAll(nonDuplicates); } else { data.addAll(toBeAdded); } } else if (value != null) { if (skipDuplicates && !(data instanceof Set) && data.contains(value)) { return data; } data.add((T) value); } return data; } }