Example usage for java.util Collection iterator

List of usage examples for java.util Collection iterator

Introduction

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

Prototype

Iterator<E> iterator();

Source Link

Document

Returns an iterator over the elements in this collection.

Usage

From source file:Main.java

@SuppressWarnings("unchecked")
public static <E> Collection<E> union(Collection<E> collectionA, Collection<E> collectionB) {
    Collection<E> collectionC = null;
    try {/*from   ww w .  jav a2  s.c o  m*/
        collectionC = collectionA.getClass().newInstance();
    } catch (Exception e) {
        e.printStackTrace();
        return collectionC;
    }
    Iterator<E> aIterator = collectionA.iterator();
    Iterator<E> bIterator = collectionB.iterator();
    while (aIterator.hasNext() || bIterator.hasNext()) {
        if (aIterator.hasNext()) {
            E ae = aIterator.next();
            if (!collectionC.contains(ae)) {
                collectionC.add(ae);
            }
        }
        if (bIterator.hasNext()) {
            E be = bIterator.next();
            if (!collectionA.contains(be) && !collectionC.contains(be)) {
                collectionC.add(be);
            }
        }
    }
    return collectionC;
}

From source file:Main.java

/**
 * Returns a String representation of this collection.
 * The items are converted to strings using String.format(frmtPattern).
 * If frmtPattern is given, the items will be formatted as
 * String.format(Object, frmtPattern), else it will use String.valueOf(Object).
 * If separatedby is given, the items will be separated by that string.
 *
 * @param c/*  ww w  .  j a  v a2s .co m*/
 * @param separatedBy
 * @return
 */
public static String toString(Collection c, String separatedBy/*, String frmtPattern*/) {

    if (c == null || c.size() == 0)
        return "";

    //        boolean usePattern = frmtPattern != null;
    StringBuffer sb = new StringBuffer();
    for (Iterator itr = c.iterator(); itr.hasNext();) {
        Object o = itr.next();
        //            String s = usePattern ? String.format(frmtPattern, o) : String.valueOf(o);
        String s = String.valueOf(o);
        sb.append(s);
        if (separatedBy != null && itr.hasNext()) {
            sb.append(separatedBy);
        }
    }

    return sb.toString();
}

From source file:com.salesmanager.core.util.MerchantConfigurationUtil.java

/**
 * Build a line with delimiter/* w  ww  . j  av a2s . com*/
 * 
 * @param configs
 * @param delimiter
 * @return
 */
public static String buildConfigurationLine(Collection<String> configs, String delimiter) {
    StringBuffer keyLine = new StringBuffer();

    if (configs != null && configs.size() > 0) {
        int count = 1;
        Iterator i = configs.iterator();
        while (i.hasNext()) {
            String s = (String) i.next();
            keyLine.append(s);
            if (count < configs.size()) {
                keyLine.append(delimiter);
            }
            count++;
        }
    }

    return keyLine.toString();

}

From source file:com.hihframework.core.utils.CollectionUtils.java

/**
 * ?ID?,???.//from  www  .  java  2s. c o m
 * http?????idhibernate???????
 * ?
 * ???ID?,ID?ID??.
 * 
 * @param collection
 *            ??
 * @param checkedIds
 *            ?
 * @param idName
 *            ID??
 * @param clazz
 *            ?
 */
public static <T, ID> void mergeByCheckedIds(Collection<T> collection, Collection<ID> checkedIds, String idName,
        Class<T> clazz) throws Exception {

    if (checkedIds == null) {
        collection.clear();
        return;
    }

    Iterator<T> it = collection.iterator();

    while (it.hasNext()) {
        T obj = it.next();
        if (checkedIds.contains(PropertyUtils.getProperty(obj, idName))) {
            checkedIds.remove(PropertyUtils.getProperty(obj, idName));
        } else {
            it.remove();
        }
    }

    for (ID id : checkedIds) {
        T obj = clazz.newInstance();
        PropertyUtils.setProperty(obj, idName, id);
        collection.add(obj);
    }
}

From source file:net.sourceforge.fenixedu.applicationTier.Servico.publico.ReadAllStudentsAndGroups.java

@Atomic
public static InfoSiteStudentsAndGroups run(String groupingId) throws FenixServiceException {
    InfoSiteStudentsAndGroups infoSiteStudentsAndGroups = new InfoSiteStudentsAndGroups();

    Grouping grouping = FenixFramework.getDomainObject(groupingId);

    if (grouping == null) {
        throw new ExistingServiceException();
    }/*  w ww . j a  va2  s.  com*/

    List infoSiteStudentsAndGroupsList = new ArrayList();
    List studentGroups = getAllStudentGroups(grouping);
    Iterator iterStudentGroups = studentGroups.iterator();
    while (iterStudentGroups.hasNext()) {

        Collection studentGroupAttendList;
        StudentGroup studentGroup = (StudentGroup) iterStudentGroups.next();

        studentGroupAttendList = studentGroup.getAttendsSet();

        Iterator iterStudentGroupAttendList = studentGroupAttendList.iterator();
        InfoSiteStudentInformation infoSiteStudentInformation = null;
        InfoSiteStudentAndGroup infoSiteStudentAndGroup = null;
        Attends attend = null;

        while (iterStudentGroupAttendList.hasNext()) {
            infoSiteStudentInformation = new InfoSiteStudentInformation();
            infoSiteStudentAndGroup = new InfoSiteStudentAndGroup();

            attend = (Attends) iterStudentGroupAttendList.next();

            infoSiteStudentAndGroup.setInfoStudentGroup(InfoStudentGroup.newInfoFromDomain(studentGroup));

            infoSiteStudentInformation.setNumber(attend.getRegistration().getNumber());

            infoSiteStudentInformation.setName(attend.getRegistration().getPerson().getName());

            infoSiteStudentInformation.setUsername((attend.getRegistration().getPerson().getUsername()));

            infoSiteStudentInformation.setEmail(attend.getRegistration().getPerson().getEmail());

            infoSiteStudentInformation.setPersonID(attend.getRegistration().getPerson().getExternalId());

            infoSiteStudentAndGroup.setInfoSiteStudentInformation(infoSiteStudentInformation);

            infoSiteStudentsAndGroupsList.add(infoSiteStudentAndGroup);
        }
    }

    Collections.sort(infoSiteStudentsAndGroupsList, new BeanComparator("infoStudentGroup.groupNumber"));

    infoSiteStudentsAndGroups.setInfoSiteStudentsAndGroupsList(infoSiteStudentsAndGroupsList);
    infoSiteStudentsAndGroups.setInfoGrouping(InfoGrouping.newInfoFromDomain(grouping));

    return infoSiteStudentsAndGroups;
}

From source file:gov.nih.nci.caintegrator.ui.graphing.util.ImageMapUtil.java

/**
 * Get a collection of entities with the area shape equal to the bounding rectangle
 * for the shape of original entity. This is necessary because the Javascript for the sample 
 * selection lasso can only handle rect objects.
 * @param entities/*from w  ww  . j a  va  2s  .co m*/
 * @return a collection of entities containing the bounding rectangles of the original entities
 */
private static Collection<ChartEntity> getBoundingEntities(Collection entities) {
    ChartEntity entity;
    ChartEntity boundingEntity;
    Shape shape;
    Rectangle2D boundingRect;
    Collection<ChartEntity> boundingEntities = new ArrayList<ChartEntity>();
    for (Iterator i = entities.iterator(); i.hasNext();) {
        entity = (ChartEntity) i.next();
        shape = entity.getArea();
        boundingRect = shape.getBounds2D();
        boundingEntity = new ChartEntity(boundingRect, entity.getToolTipText(), entity.getURLText());
        boundingEntities.add(boundingEntity);
    }
    return boundingEntities;
}

From source file:com.neusoft.mid.clwapi.tools.JacksonUtils.java

/**
 * @param obj/*  w w  w . j  a v a  2 s .co m*/
 * @param f
 * @throws IllegalAccessException
 * @throws JacksonEncoderException
 */
private static Object jsonCoder(Object obj, Field f) throws IllegalAccessException, JacksonEncoderException {
    Object o = FieldUtils.readField(f, obj);
    if (o instanceof String) {
        FieldUtils.writeField(f, obj, jsonCoder((String) o, true));
    } else if (o instanceof Collection<?>) {
        logger.debug("Field [" + f.getName() + "] is " + o.getClass());
        Collection<?> c = (Collection<?>) o;
        Iterator<?> it = c.iterator();
        while (it.hasNext()) {
            jsonEncoder(it.next());
        }
    } else if (o instanceof Map<?, ?>) {
        logger.debug("Field [" + f.getName() + "] is " + o.getClass());
        Set<?> entries = ((Map<?, ?>) o).entrySet();
        Iterator<?> it = entries.iterator();
        while (it.hasNext()) {
            Map.Entry<Object, Object> entry = (Map.Entry<Object, Object>) it.next();
            logger.debug("Key is [" + entry.getKey() + "]");
            entry.setValue(jsonEncoder(entry.getValue()));
        }
    } else if (o instanceof Integer || o instanceof Byte || o instanceof Boolean || o instanceof Long
            || o instanceof Double || o instanceof Character || o instanceof Short || o instanceof Float
            || o instanceof Number) {
        return obj;
    } else {
        throw new JacksonEncoderException("??" + f.getClass());
    }
    return obj;
}

From source file:info.magnolia.cms.util.ClasspathResourcesUtil.java

/**
 * Load resources from jars or directories
 *
 * @param resources found resources will be added to this collection
 * @param jarOrDir  a File, can be a jar or a directory
 * @param filter    used to filter resources
 *///from   ww  w .  ja  v  a 2 s.  c  o m
private static void collectFiles(Collection resources, File jarOrDir, Filter filter) {

    if (!jarOrDir.exists()) {
        log.warn("missing file: {}", jarOrDir.getAbsolutePath());
        return;
    }

    if (jarOrDir.isDirectory()) {
        if (log.isDebugEnabled())
            log.debug("looking in dir {}", jarOrDir.getAbsolutePath());

        Collection files = FileUtils.listFiles(jarOrDir, new TrueFileFilter() {
        }, new TrueFileFilter() {
        });
        for (Iterator iter = files.iterator(); iter.hasNext();) {
            File file = (File) iter.next();
            String name = StringUtils.substringAfter(file.getPath(), jarOrDir.getPath());

            // please, be kind to Windows!!!
            name = StringUtils.replace(name, "\\", "/");
            if (!name.startsWith("/")) {
                name = "/" + name;
            }

            if (filter.accept(name)) {
                resources.add(name);
            }
        }
    } else if (jarOrDir.getName().endsWith(".jar")) {
        if (log.isDebugEnabled())
            log.debug("looking in jar {}", jarOrDir.getAbsolutePath());
        JarFile jar;
        try {
            jar = new JarFile(jarOrDir);
        } catch (IOException e) {
            log.error("IOException opening file {}, skipping", jarOrDir.getAbsolutePath());
            return;
        }
        for (Enumeration em = jar.entries(); em.hasMoreElements();) {
            JarEntry entry = (JarEntry) em.nextElement();
            if (!entry.isDirectory()) {
                if (filter.accept("/" + entry.getName())) {
                    resources.add("/" + entry.getName());
                }
            }
        }
    } else {
        if (log.isDebugEnabled())
            log.debug("Unknown (not jar) file in classpath: {}, skipping.", jarOrDir.getName());
    }

}

From source file:net.buffalo.protocal.util.ClassUtil.java

public static Object convertValue(Object value, Class targetType) {

    if (value.getClass().equals(targetType))
        return value;

    if (targetType.isPrimitive()) {
        targetType = getWrapperClass(targetType);
    }//from  ww w .  j a va2s  .c  o m

    if (targetType.isAssignableFrom(value.getClass()))
        return value;

    if ((value instanceof String || value instanceof Number) && Number.class.isAssignableFrom(targetType)) {
        try {
            Constructor ctor = targetType.getConstructor(new Class[] { String.class });
            return ctor.newInstance(new Object[] { value.toString() });
        } catch (Exception e) {
            LOGGER.error("convert type error", e);
            throw new RuntimeException(
                    "Cannot convert from " + value.getClass().getName() + " to " + targetType, e);
        }
    }

    if (targetType.isArray() && Collection.class.isAssignableFrom(value.getClass())) {
        Collection collection = (Collection) value;
        Object array = Array.newInstance(targetType.getComponentType(), collection.size());
        int i = 0;
        for (Iterator iter = collection.iterator(); iter.hasNext();) {
            Object val = iter.next();
            Array.set(array, i++, val);
        }

        return array;
    }

    if (Collection.class.isAssignableFrom(targetType) && value.getClass().isArray()) {
        return Arrays.asList((Object[]) value);
    }

    throw new IllegalArgumentException(
            "Cannot convert from " + value.getClass().getName() + " to " + targetType);
}

From source file:de.dhke.projects.cutil.collections.CollectionUtil.java

public static <T> String transformedToString(final Collection<? extends T> collection,
        final Transformer<T, ?> stringer) {
    final StringBuilder sb = new StringBuilder(3 * collection.size());
    sb.append("[");
    final Iterator<? extends T> iter = collection.iterator();
    if (iter.hasNext())
        sb.append(stringer.transform(iter.next()));
    while (iter.hasNext()) {
        sb.append(", ");
        sb.append(stringer.transform(iter.next()));
    }//from   w  ww  . j a  va2 s . co  m
    sb.append("]");
    return sb.toString();
}