Example usage for java.util Collection addAll

List of usage examples for java.util Collection addAll

Introduction

In this page you can find the example usage for java.util Collection addAll.

Prototype

boolean addAll(Collection<? extends E> c);

Source Link

Document

Adds all of the elements in the specified collection to this collection (optional operation).

Usage

From source file:Main.java

/**
 * Join several all provided collections in the first one provided.<br />
 * The instance of the target collection is returned to ease use in foreach loops.
 * @param <T>/*  w ww. j av  a2  s .c  o m*/
 *        the type of the elements contained in the collection.
 * @param target
 *        the target collection
 * @param collections
 *        the collections of items to add in the target collection.
 * @return the first collection, with the other items of the collection added.
 */
@SafeVarargs
public static <T> Collection<T> joinCollections(final Collection<T> target,
        final Collection<? extends T>... collections) {
    if (target == null) {
        throw new IllegalArgumentException("Cannot join collection in null target");
    }
    if (collections.length == 0) {
        return target;
    }

    for (final Collection<? extends T> collection : collections) {
        target.addAll(collection);
    }
    return target;
}

From source file:Main.java

/**
 * Removes duplicate objects from the Collection.
 * @param p_collection a Collection/*from  w  ww. j av  a 2 s . c  o  m*/
 * @returns true if one or more duplicate objects were removed.
 */
public static boolean removeDuplicates(Collection p_collection) {
    if (p_collection == null) {
        return false;
    }
    HashSet set = new HashSet(p_collection.size());
    Iterator it = p_collection.iterator();
    while (it.hasNext()) {
        set.add(it.next());
    }
    if (set.size() != p_collection.size()) {
        p_collection.clear();
        p_collection.addAll(set);
        return true;
    }
    return false;
}

From source file:ch.sdi.core.impl.cfg.ConfigUtils.java

/**
 * Returns a collection of all property names in the environment.
 * <p>//from   w w  w  .  j  ava2s  .  com
 * @param aEnv
 * @return
 */
public static Collection<String> getAllPropertyNames(ConfigurableEnvironment aEnv) {
    Collection<String> result = new HashSet<>();
    aEnv.getPropertySources().forEach(ps -> result.addAll(getAllPropertyNames(ps)));
    return result;
}

From source file:Main.java

/**
 * convert value to given type.//from  ww  w .  ja v a 2  s  . co  m
 * null safe.
 *
 * @param value value for convert
 * @param type  will converted type
 * @return value while converted
 */
public static Object convertCompatibleType(Object value, Class<?> type) {

    if (value == null || type == null || type.isAssignableFrom(value.getClass())) {
        return value;
    }
    if (value instanceof String) {
        String string = (String) value;
        if (char.class.equals(type) || Character.class.equals(type)) {
            if (string.length() != 1) {
                throw new IllegalArgumentException(String.format("CAN NOT convert String(%s) to char!"
                        + " when convert String to char, the String MUST only 1 char.", string));
            }
            return string.charAt(0);
        } else if (type.isEnum()) {
            return Enum.valueOf((Class<Enum>) type, string);
        } else if (type == BigInteger.class) {
            return new BigInteger(string);
        } else if (type == BigDecimal.class) {
            return new BigDecimal(string);
        } else if (type == Short.class || type == short.class) {
            return Short.valueOf(string);
        } else if (type == Integer.class || type == int.class) {
            return Integer.valueOf(string);
        } else if (type == Long.class || type == long.class) {
            return Long.valueOf(string);
        } else if (type == Double.class || type == double.class) {
            return Double.valueOf(string);
        } else if (type == Float.class || type == float.class) {
            return Float.valueOf(string);
        } else if (type == Byte.class || type == byte.class) {
            return Byte.valueOf(string);
        } else if (type == Boolean.class || type == boolean.class) {
            return Boolean.valueOf(string);
        } else if (type == Date.class) {
            try {
                return new SimpleDateFormat(DATE_FORMAT).parse((String) value);
            } catch (ParseException e) {
                throw new IllegalStateException("Failed to parse date " + value + " by format " + DATE_FORMAT
                        + ", cause: " + e.getMessage(), e);
            }
        } else if (type == Class.class) {
            return forName((String) value);
        }
    } else if (value instanceof Number) {
        Number number = (Number) value;
        if (type == byte.class || type == Byte.class) {
            return number.byteValue();
        } else if (type == short.class || type == Short.class) {
            return number.shortValue();
        } else if (type == int.class || type == Integer.class) {
            return number.intValue();
        } else if (type == long.class || type == Long.class) {
            return number.longValue();
        } else if (type == float.class || type == Float.class) {
            return number.floatValue();
        } else if (type == double.class || type == Double.class) {
            return number.doubleValue();
        } else if (type == BigInteger.class) {
            return BigInteger.valueOf(number.longValue());
        } else if (type == BigDecimal.class) {
            return BigDecimal.valueOf(number.doubleValue());
        } else if (type == Date.class) {
            return new Date(number.longValue());
        }
    } else if (value instanceof Collection) {
        Collection collection = (Collection) value;
        if (type.isArray()) {
            int length = collection.size();
            Object array = Array.newInstance(type.getComponentType(), length);
            int i = 0;
            for (Object item : collection) {
                Array.set(array, i++, item);
            }
            return array;
        } else if (!type.isInterface()) {
            try {
                Collection result = (Collection) type.newInstance();
                result.addAll(collection);
                return result;
            } catch (Throwable e) {
                e.printStackTrace();
            }
        } else if (type == List.class) {
            return new ArrayList<>(collection);
        } else if (type == Set.class) {
            return new HashSet<>(collection);
        }
    } else if (value.getClass().isArray() && Collection.class.isAssignableFrom(type)) {
        Collection collection;
        if (!type.isInterface()) {
            try {
                collection = (Collection) type.newInstance();
            } catch (Throwable e) {
                collection = new ArrayList<>();
            }
        } else if (type == Set.class) {
            collection = new HashSet<>();
        } else {
            collection = new ArrayList<>();
        }
        int length = Array.getLength(value);
        for (int i = 0; i < length; i++) {
            collection.add(Array.get(value, i));
        }
        return collection;
    }
    return value;
}

From source file:de.undercouch.citeproc.helper.Levenshtein.java

/**
 * Searches the given collection of strings and returns a collection of
 * strings similar to a given string <code>t</code>. Uses reasonable default
 * values for human-readable strings. The returned collection will be
 * sorted according to their similarity with the string with the best
 * match at the first position.//  w  w w.j av  a 2 s  .c o m
 * @param <T> the type of the strings in the given collection
 * @param ss the collection to search
 * @param t the string to compare to
 * @return a collection with similar strings
 */
public static <T extends CharSequence> Collection<T> findSimilar(Collection<T> ss, CharSequence t) {
    //look for strings prefixed by 't'
    Collection<T> result = new LinkedHashSet<T>();
    for (T s : ss) {
        if (StringUtils.startsWithIgnoreCase(s, t)) {
            result.add(s);
        }
    }

    //find strings according to their levenshtein distance
    Collection<T> mins = findMinimum(ss, t, 5, Math.min(t.length() - 1, 7));
    result.addAll(mins);

    return result;
}

From source file:com.dianping.lion.util.UrlUtils.java

public static String resolveUrl(Map<String, ?> parameters, String... includes) {
    StringBuilder url = new StringBuilder();
    int index = 0;
    try {//www. j  ava  2  s  .c  o m
        if (parameters != null) {
            for (Entry<String, ?> entry : parameters.entrySet()) {
                Collection<Object> paramValues = new ArrayList<Object>();
                Object paramValue = entry.getValue();
                if (ArrayUtils.isEmpty(includes) || ArrayUtils.contains(includes, entry.getKey())) {
                    Class<? extends Object> paramClass = paramValue.getClass();
                    if (Collection.class.isInstance(paramValue)) {
                        paramValues.addAll((Collection<?>) paramValue);
                    } else if (paramClass.isArray()) {
                        Object[] valueArray = (Object[]) paramValue;
                        for (Object value : valueArray) {
                            paramValues.add(value);
                        }
                    } else {
                        paramValues.add(paramValue);
                    }
                    for (Object value : paramValues) {
                        url.append(index++ == 0 ? "" : "&").append(entry.getKey()).append("=")
                                .append(URLEncoder.encode(value.toString(), "utf-8"));
                    }
                }
            }
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    return url.toString();
}

From source file:net.sourceforge.fenixedu.presentationTier.docs.academicAdministrativeOffice.ApprovementInfoForEquivalenceProcess.java

static private void reportCycles(final StringBuilder result, final SortedSet<ICurriculumEntry> entries,
        final Map<Unit, String> academicUnitIdentifiers, final Registration registration) {
    final Collection<CycleCurriculumGroup> cycles = new TreeSet<CycleCurriculumGroup>(
            CycleCurriculumGroup.COMPARATOR_BY_CYCLE_TYPE_AND_ID);
    cycles.addAll(registration.getLastStudentCurricularPlan().getInternalCycleCurriculumGrops());

    CycleCurriculumGroup lastReported = null;
    for (final CycleCurriculumGroup cycle : cycles) {
        if (!cycle.isConclusionProcessed() || isDEARegistration(registration)) {
            // final ApprovementCertificateRequest request =
            // ((ApprovementCertificateRequest) getDocumentRequest());
            final Curriculum curriculum = cycle.getCurriculum();
            filterEntries(entries, curriculum);

            if (!entries.isEmpty()) {
                if (lastReported == null) {
                    lastReported = cycle;
                } else {
                    result.append(LINE_BREAK);
                }//from w  ww.j ava 2s. c o  m

                result.append(getMLSTextContent(cycle.getName())).append(":").append(LINE_BREAK);
                reportEntries(result, entries, academicUnitIdentifiers, registration);
            }

            entries.clear();
        }
    }
}

From source file:com.jhkt.playgroundArena.db.nosql.mongodb.beans.AbstractDocument.java

private final static Object convertBacktoClassInstanceHelper(DBObject dBObject) {

    Object returnValue = null;//w  w w  . ja  v  a2  s.  com

    try {
        String className = dBObject.get(JPAConstants.CONVERTER_CLASS.CLASS.name()).toString();
        Class<?> classCheck = Class.forName(className);

        if (AbstractDocument.class.isAssignableFrom(classCheck)) {
            Class<? extends AbstractDocument> classToConvertTo = classCheck.asSubclass(AbstractDocument.class);
            AbstractDocument dInstance = classToConvertTo.newInstance();

            for (String key : dBObject.keySet()) {
                Object value = dBObject.get(key);

                char[] propertyChars = key.toCharArray();
                String methodMain = String.valueOf(propertyChars[0]).toUpperCase() + key.substring(1);
                String methodName = "set" + methodMain;
                String getMethodName = "get" + methodMain;

                if (key.equals(JPAConstants.CONVERTER_CLASS.CLASS.name())) {
                    continue;
                }

                if (value instanceof BasicDBObject) {
                    value = convertBacktoClassInstanceHelper(BasicDBObject.class.cast(value));
                }

                try {
                    Method getMethod = classToConvertTo.getMethod(getMethodName);
                    Class<?> getReturnType = getMethod.getReturnType();
                    Method method = classToConvertTo.getMethod(methodName, getReturnType);

                    if (getMethod.isAnnotationPresent(IDocumentKeyValue.class)) {
                        method.invoke(dInstance, value);
                    }
                } catch (NoSuchMethodException nsMe) {
                    _log.warn("Within convertBacktoClassInstance, following method was not found " + methodName,
                            nsMe);
                }

            }

            returnValue = dInstance;

        } else if (Enum.class.isAssignableFrom(classCheck)) {

            List<?> constants = Arrays.asList(classCheck.getEnumConstants());
            String name = String.class.cast(dBObject.get(JPAConstants.CONVERTER_CLASS.CONTENT.name()));
            for (Object constant : constants) {
                if (constant.toString().equals(name)) {
                    returnValue = constant;
                }
            }

        } else if (Collection.class.isAssignableFrom(classCheck)) {

            @SuppressWarnings("unchecked")
            Class<? extends Collection<? super Object>> classToConvertTo = (Class<? extends Collection<? super Object>>) classCheck;
            Collection<? super Object> cInstance = classToConvertTo.newInstance();

            BasicDBList bDBList = (BasicDBList) dBObject.get(JPAConstants.CONVERTER_CLASS.CONTENT.name());
            cInstance.addAll(bDBList);

            returnValue = cInstance;

        } else if (Map.class.isAssignableFrom(classCheck)) {

            @SuppressWarnings("unchecked")
            Class<? extends Map<String, ? super Object>> classToConvertTo = (Class<? extends Map<String, ? super Object>>) classCheck;
            Map<String, ? super Object> mInstance = classToConvertTo.newInstance();

            BasicDBObject mapObject = (BasicDBObject) dBObject.get(JPAConstants.CONVERTER_CLASS.CONTENT.name());
            mInstance.putAll(mapObject);

            returnValue = mInstance;

        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return returnValue;
}

From source file:Main.java

public static Collection<Node> search_nodes_by_attribute(Node root, String attr_name, String attr_value) {
    Collection<Node> result = new LinkedList<Node>();
    if (root instanceof Element) {
        if (((Element) root).hasAttribute(attr_name)
                && ((Element) root).getAttribute(attr_name).equals(attr_value))
            result.add(root);/*from  ww w  . j  a va2s  .  co m*/
    }
    NodeList list = root.getChildNodes();
    for (int i = 0; i < list.getLength(); ++i) {
        Node child = list.item(i);
        Collection<Node> ret = search_nodes_by_attribute(child, attr_name, attr_value);
        result.addAll(ret);
    }
    return result;
}

From source file:com.newrelic.agent.AgentCommandLineParser.java

static Options getCommandLineOptions()
/* 329:    */ {// ww  w  .j ava2 s. c om
    /* 330:295 */ Collection<Options> values = new ArrayList(Collections.singletonList(getBasicOptions()));
    /* 331:296 */ values.addAll(commandOptionsMap.values());
    /* 332:297 */ return combineOptions(values);
    /* 333:    */ }