Example usage for java.util Iterator remove

List of usage examples for java.util Iterator remove

Introduction

In this page you can find the example usage for java.util Iterator remove.

Prototype

default void remove() 

Source Link

Document

Removes from the underlying collection the last element returned by this iterator (optional operation).

Usage

From source file:jp.ac.tokushima_u.is.ll.common.orm.hibernate.HibernateWebUtils.java

/**
 * ?ID?,???.//from   w  w w .  j a  v  a 2s . c o  m
 * 
 * ??????id,??????id?????.
 * ???id??,??id??.
 * ?ID, ??cascade-save-or-update.
 * 
 * @param srcObjects ??,.
 * @param checkedIds  ?,ID.
 * @param clazz  ?
 * @param idName ??
 */
public static <T, ID> void mergeByCheckedIds(final Collection<T> srcObjects, final Collection<ID> checkedIds,
        final Class<T> clazz, final String idName) {

    //?
    Assert.notNull(srcObjects, "scrObjects?");
    Assert.hasText(idName, "idName?");
    Assert.notNull(clazz, "clazz?");

    //?,???.
    if (checkedIds == null) {
        srcObjects.clear();
        return;
    }

    //????,id?ID?,.
    //?,???id,?id???ID.
    Iterator<T> srcIterator = srcObjects.iterator();
    try {

        while (srcIterator.hasNext()) {
            T element = srcIterator.next();
            Object id;
            id = PropertyUtils.getProperty(element, idName);

            if (!checkedIds.contains(id)) {
                srcIterator.remove();
            } else {
                checkedIds.remove(id);
            }
        }

        //ID??id????,,id??.
        for (ID id : checkedIds) {
            T obj = clazz.newInstance();
            PropertyUtils.setProperty(obj, idName, id);
            srcObjects.add(obj);
        }
    } catch (Exception e) {
        throw ReflectionUtils.convertReflectionExceptionToUnchecked(e);
    }
}

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

@Atomic
public static List run(String departmentId, String executionYearID, Integer semester, Integer teacherType)
        throws FenixServiceException {

    ExecutionYear executionYear = null;/*from   w w  w  .jav a 2s. co  m*/
    if (executionYearID != null) {
        executionYear = FenixFramework.getDomainObject(executionYearID);
    }

    final ExecutionSemester executionSemester = executionYear.getExecutionSemesterFor(semester);
    if (semester.intValue() != 0 && executionSemester == null) {
        throw new FenixServiceException("error.noExecutionPeriod");
    }

    final Department department = FenixFramework.getDomainObject(departmentId);
    if (department == null) {
        throw new FenixServiceException("error.noDepartment");
    }

    final List<Teacher> teachers = department.getAllCurrentTeachers();

    Iterator iter = teachers.iterator();

    List professorships = new ArrayList();
    List responsibleFors = new ArrayList();
    while (iter.hasNext()) {
        Teacher teacher = (Teacher) iter.next();
        Collection teacherProfessorships = null;
        if (executionYear == null) {
            teacherProfessorships = teacher.getProfessorships();
        } else {
            if (semester.intValue() == 0) {
                teacherProfessorships = teacher.getProfessorships(executionYear);
            } else {
                teacherProfessorships = teacher.getProfessorships(executionSemester);
            }
        }
        if (teacherProfessorships != null) {
            professorships.addAll(teacherProfessorships);
        }

        List teacherResponsibleFors;
        List<Professorship> teacherResponsibleForsAux = null;

        if (executionYear == null) {
            teacherResponsibleFors = teacher.responsibleFors();
        } else {
            teacherResponsibleForsAux = teacher.responsibleFors();
            teacherResponsibleFors = new ArrayList<Professorship>();
            for (Professorship professorship : teacherResponsibleForsAux) {
                if (professorship.getExecutionCourse().getExecutionPeriod().getExecutionYear()
                        .equals(executionYear)) {
                    teacherResponsibleFors.add(professorship);
                }
            }
        }
        if (teacherResponsibleFors != null) {
            responsibleFors.addAll(teacherResponsibleFors);
        }
    }

    List detailedProfessorships = getDetailedProfessorships(professorships, responsibleFors, teacherType);

    // Cleaning out possible null elements inside the list
    Iterator itera = detailedProfessorships.iterator();
    while (itera.hasNext()) {
        Object dp = itera.next();
        if (dp == null) {
            itera.remove();
        }
    }

    Collections.sort(detailedProfessorships, new Comparator() {

        @Override
        public int compare(Object o1, Object o2) {

            DetailedProfessorship detailedProfessorship1 = (DetailedProfessorship) o1;
            DetailedProfessorship detailedProfessorship2 = (DetailedProfessorship) o2;
            int result = detailedProfessorship1.getInfoProfessorship().getInfoExecutionCourse().getExternalId()
                    .compareTo(detailedProfessorship2.getInfoProfessorship().getInfoExecutionCourse()
                            .getExternalId());
            if (result == 0 && (detailedProfessorship1.getResponsibleFor().booleanValue()
                    || detailedProfessorship2.getResponsibleFor().booleanValue())) {
                if (detailedProfessorship1.getResponsibleFor().booleanValue()) {
                    return -1;
                }
                if (detailedProfessorship2.getResponsibleFor().booleanValue()) {
                    return 1;
                }
            }

            return result;
        }

    });

    List result = new ArrayList();
    iter = detailedProfessorships.iterator();
    List temp = new ArrayList();
    while (iter.hasNext()) {
        DetailedProfessorship detailedProfessorship = (DetailedProfessorship) iter.next();
        if (temp.isEmpty() || ((DetailedProfessorship) temp.get(temp.size() - 1)).getInfoProfessorship()
                .getInfoExecutionCourse()
                .equals(detailedProfessorship.getInfoProfessorship().getInfoExecutionCourse())) {
            temp.add(detailedProfessorship);
        } else {
            result.add(temp);
            temp = new ArrayList();
            temp.add(detailedProfessorship);
        }
    }
    if (!temp.isEmpty()) {
        result.add(temp);
    }
    return result;
}

From source file:edu.uci.ics.hyracks.control.cc.partitions.PartitionMatchMaker.java

private static <T> void removeEntries(Map<PartitionId, List<T>> map, IEntryFilter<T> filter) {
    Iterator<Map.Entry<PartitionId, List<T>>> i = map.entrySet().iterator();
    while (i.hasNext()) {
        Map.Entry<PartitionId, List<T>> e = i.next();
        List<T> list = e.getValue();
        removeEntries(list, filter);/*from  w  w w.  j  a  v a  2s  .  c  o  m*/
        if (list.isEmpty()) {
            i.remove();
        }
    }
}

From source file:com.framework.infrastructure.utils.HibernateUtils.java

/**
 * ID,./*from ww w  .  jav a  2s . c o  m*/
 * 
 * id,id.
 * id,id. ID,
 * cascade-save-or-update.
 * 
 * @param srcObjects
 *            ,.
 * @param checkedIds
 *            ,ID.
 * @param clazz
 *            
 * @param idName
 *            
 */
public static <T, ID> void mergeByCheckedIds(final Collection<T> srcObjects, final Collection<ID> checkedIds,
        final Class<T> clazz, final String idName) {

    // 
    Assert.notNull(srcObjects, "scrObjects");
    Assert.hasText(idName, "idName");
    Assert.notNull(clazz, "clazz");

    // , .
    if (checkedIds == null) {
        srcObjects.clear();
        return;
    }

    // ,idID,.
    // ,id,idid.
    Iterator<T> srcIterator = srcObjects.iterator();
    try {

        while (srcIterator.hasNext()) {
            T element = srcIterator.next();
            Object id;
            id = PropertyUtils.getProperty(element, idName);

            if (!checkedIds.contains(id)) {
                srcIterator.remove();
            } else {
                checkedIds.remove(id);
            }
        }

        // IDid,,id.
        for (ID id : checkedIds) {
            T obj = clazz.newInstance();
            PropertyUtils.setProperty(obj, idName, id);
            srcObjects.add(obj);
        }
    } catch (Exception e) {
        throw ReflectionUtils.convertReflectionExceptionToUnchecked(e);
    }
}

From source file:com.afeng.common.dao.orm.HibernateWebUtils.java

/**
 * ?ID?,???./*from   w w w  . j a  va  2  s.  c o m*/
 * <p/>
 * ??????id,??????id?????.
 * ???id??,??id??.
 * ?ID, ??cascade-save-or-update.
 *
 * @param srcObjects ??,.
 * @param checkedIds ?,ID.
 * @param clazz      ?
 * @param idName     ??
 */
public static <T, ID> void mergeByCheckedIds(final Collection<T> srcObjects, final Collection<ID> checkedIds,
        final Class<T> clazz, final String idName) {

    //?
    Assert.notNull(srcObjects, "scrObjects?");
    Assert.hasText(idName, "idName?");
    Assert.notNull(clazz, "clazz?");

    //?,???.
    if (checkedIds == null) {
        srcObjects.clear();
        return;
    }

    //????,id?ID?,.
    //?,???id,?id???id.
    Iterator<T> srcIterator = srcObjects.iterator();
    try {

        while (srcIterator.hasNext()) {
            T element = srcIterator.next();
            Object id;
            id = PropertyUtils.getProperty(element, idName);

            if (!checkedIds.contains(id)) {
                srcIterator.remove();
            } else {
                checkedIds.remove(id);
            }
        }

        //ID??id????,,id??.
        for (ID id : checkedIds) {
            T obj = clazz.newInstance();
            PropertyUtils.setProperty(obj, idName, id);
            srcObjects.add(obj);
        }
    } catch (Exception e) {
        throw ReflectionUtils.convertReflectionExceptionToUnchecked(e);
    }
}

From source file:Main.java

/**
 * Returns 0 if empty iterable//from   w ww. ja v a2s.c  o m
 * */
public static double computeAverage(Iterable<Double> iterable) {
    synchronized (iterable) {
        Iterator<Double> iterator = iterable.iterator();
        int numberOfElements = 0;
        double sum = 0;
        while (iterator.hasNext()) {
            Double value = iterator.next();
            // FIXME the point is: why next() return null if the addition of
            // null objects is prevented in the circular fifo queue?
            // Investigate the question...
            if (value == null) {
                iterator.remove();
                System.out.println("null in iterator. sum: " + sum);
            } else {
                sum += value;
                numberOfElements++;
            }
        }
        // System.out.println("sum: " + sum + "; numner of elements: " +
        // numberOfElements);
        if (numberOfElements == 0) {
            return 0;
        }
        return sum / numberOfElements;
    }
}

From source file:Main.java

/**
 * Finds the most optimal size. The optimal size is when possible the same as
 * the camera resolution, if not is is it the best size between the camera solution and
 * MIN_SIZE_PIXELS//from  ww w  .j a  v a  2  s  . c  o  m
 * @param screenResolution
 * @param rawSupportedSizes
 *@param defaultCameraSize @return optimal preview size
 */
private static Point findBestSizeValue(Point screenResolution, List<Camera.Size> rawSupportedSizes,
        Camera.Size defaultCameraSize) {

    if (rawSupportedSizes == null) {
        Log.w(TAG, "Device returned no supported sizes; using default");
        if (defaultCameraSize == null) {
            throw new IllegalStateException("Parameters contained no size!");
        }
        return new Point(defaultCameraSize.width, defaultCameraSize.height);
    }

    // Sort by size, descending
    List<Camera.Size> supportedSizes = new ArrayList<>(rawSupportedSizes);
    Collections.sort(supportedSizes, new Comparator<Camera.Size>() {
        @Override
        public int compare(Camera.Size a, Camera.Size b) {
            int aPixels = a.height * a.width;
            int bPixels = b.height * b.width;
            if (bPixels > aPixels) {
                return -1;
            }
            if (bPixels < aPixels) {
                return 1;
            }
            return 0;
        }
    });

    if (Log.isLoggable(TAG, Log.INFO)) {
        StringBuilder sizesString = new StringBuilder();
        for (Camera.Size supportedSize : supportedSizes) {
            sizesString.append(supportedSize.width).append('x').append(supportedSize.height).append(' ');
        }
        Log.i(TAG, "Supported sizes: " + sizesString);
    }

    double screenAspectRatio = (double) screenResolution.x / (double) screenResolution.y;

    // Remove sizes that are unsuitable
    Iterator<Camera.Size> it = supportedSizes.iterator();
    while (it.hasNext()) {
        Camera.Size supportedSize = it.next();
        int realWidth = supportedSize.width;
        int realHeight = supportedSize.height;
        if (realWidth * realHeight < MIN_SIZE_PIXELS) {
            it.remove();
            continue;
        }

        boolean isCandidatePortrait = realWidth < realHeight;
        int maybeFlippedWidth = isCandidatePortrait ? realHeight : realWidth;
        int maybeFlippedHeight = isCandidatePortrait ? realWidth : realHeight;
        double aspectRatio = (double) maybeFlippedWidth / (double) maybeFlippedHeight;
        double distortion = Math.abs(aspectRatio - screenAspectRatio);
        if (distortion > MAX_ASPECT_DISTORTION) {
            it.remove();
            continue;
        }

        if (maybeFlippedWidth == screenResolution.x && maybeFlippedHeight == screenResolution.y) {
            Point exactPoint = new Point(realWidth, realHeight);
            Log.i(TAG, "Found size exactly matching screen size: " + exactPoint);
            return exactPoint;
        }
    }

    // If no exact match, use largest size. This was not a great idea on older devices because
    // of the additional computation needed. We're likely to get here on newer Android 4+ devices, where
    // the CPU is much more powerful.
    if (!supportedSizes.isEmpty()) {
        Camera.Size largestCameraSizes = supportedSizes.get(0);
        Point largestSize = new Point(largestCameraSizes.width, largestCameraSizes.height);
        Log.i(TAG, "Using largest suitable size: " + largestSize);
        return largestSize;
    }

    // If there is nothing at all suitable, return current size
    if (defaultCameraSize == null) {
        throw new IllegalStateException("Parameters contained no size!");
    }
    Point defaultSize = new Point(defaultCameraSize.width, defaultCameraSize.height);
    Log.i(TAG, "No suitable sizes, using default: " + defaultSize);

    return defaultSize;
}

From source file:io.github.swagger2markup.MarkdownConverterTest.java

/**
 * Given a markdown document to search, this checks to see if the specified tables
 * have all of the expected fields listed.
 * Match is a "search", and not an "equals" match.
 *
 * @param doc           markdown document file to inspect
 * @param fieldsByTable map of table name (header) to field names expected
 *                      to be found in that table.
 * @throws IOException if the markdown document could not be read
 *///from w  w  w  . ja  v  a  2  s  .c  om
private static void verifyMarkdownContainsFieldsInTables(File doc, Map<String, Set<String>> fieldsByTable)
        throws IOException {
    //TODO: This method is too complex, split it up in smaller methods to increase readability
    final List<String> lines = Files.readAllLines(doc.toPath(), Charset.defaultCharset());
    final Map<String, Set<String>> fieldsLeftByTable = Maps.newHashMap();
    for (Map.Entry<String, Set<String>> entry : fieldsByTable.entrySet()) {
        fieldsLeftByTable.put(entry.getKey(), Sets.newHashSet(entry.getValue()));
    }
    String inTable = null;
    for (String line : lines) {
        // If we've found every field we care about, quit early
        if (fieldsLeftByTable.isEmpty()) {
            return;
        }

        // Transition to a new table if we encounter a header
        final String currentHeader = getTableHeader(line);
        if (inTable == null || currentHeader != null) {
            inTable = currentHeader;
        }

        // If we're in a table that we care about, inspect this potential table row
        if (inTable != null && fieldsLeftByTable.containsKey(inTable)) {
            // If we're still in a table, read the row and check for the field name
            //  NOTE: If there was at least one pipe, then there's at least 2 fields
            String[] parts = line.split("\\|");
            if (parts.length > 1) {
                final String fieldName = parts[1];
                final Set<String> fieldsLeft = fieldsLeftByTable.get(inTable);
                // Mark the field as found and if this table has no more fields to find,
                //  remove it from the "fieldsLeftByTable" map to mark the table as done
                Iterator<String> fieldIt = fieldsLeft.iterator();
                while (fieldIt.hasNext()) {
                    String fieldLeft = fieldIt.next();
                    if (fieldName.contains(fieldLeft))
                        fieldIt.remove();
                }
                if (fieldsLeft.isEmpty()) {
                    fieldsLeftByTable.remove(inTable);
                }
            }
        }
    }

    // After reading the file, if there were still types, fail
    if (!fieldsLeftByTable.isEmpty()) {
        fail(String.format("Markdown file '%s' did not contain expected fields (by table): %s", doc,
                fieldsLeftByTable));
    }
}

From source file:Main.java

public static Point findBestPreviewSizeValue(Camera.Parameters parameters, Point screenResolution) {

    List<Size> rawSupportedSizes = parameters.getSupportedPreviewSizes();
    if (rawSupportedSizes == null) {
        Log.w(TAG, "Device returned no supported preview sizes; using default");
        Size defaultSize = parameters.getPreviewSize();
        if (defaultSize == null) {
            throw new IllegalStateException("Parameters contained no preview size!");
        }// w  ww.j  a v a 2s.  com
        return new Point(defaultSize.width, defaultSize.height);
    }

    // Sort by size, descending
    List<Size> supportedPreviewSizes = new ArrayList<Size>(rawSupportedSizes);
    Collections.sort(supportedPreviewSizes, new Comparator<Size>() {
        @Override
        public int compare(Size a, Size b) {
            int aPixels = a.height * a.width;
            int bPixels = b.height * b.width;
            if (bPixels < aPixels) {
                return -1;
            }
            if (bPixels > aPixels) {
                return 1;
            }
            return 0;
        }
    });

    if (Log.isLoggable(TAG, Log.INFO)) {
        StringBuilder previewSizesString = new StringBuilder();
        for (Size supportedPreviewSize : supportedPreviewSizes) {
            previewSizesString.append(supportedPreviewSize.width).append('x')
                    .append(supportedPreviewSize.height).append(' ');
        }
        Log.i(TAG, "Supported preview sizes: " + previewSizesString);
    }

    double screenAspectRatio = (double) screenResolution.x / (double) screenResolution.y;

    // Remove sizes that are unsuitable
    Iterator<Size> it = supportedPreviewSizes.iterator();
    while (it.hasNext()) {
        Size supportedPreviewSize = it.next();
        int realWidth = supportedPreviewSize.width;
        int realHeight = supportedPreviewSize.height;
        if (realWidth * realHeight < MIN_PREVIEW_PIXELS) {
            it.remove();
            continue;
        }

        boolean isCandidatePortrait = realWidth < realHeight;
        int maybeFlippedWidth = isCandidatePortrait ? realHeight : realWidth;
        int maybeFlippedHeight = isCandidatePortrait ? realWidth : realHeight;
        double aspectRatio = (double) maybeFlippedWidth / (double) maybeFlippedHeight;
        double distortion = Math.abs(aspectRatio - screenAspectRatio);
        if (distortion > MAX_ASPECT_DISTORTION) {
            it.remove();
            continue;
        }

        if (maybeFlippedWidth == screenResolution.x && maybeFlippedHeight == screenResolution.y) {
            Point exactPoint = new Point(realWidth, realHeight);
            Log.i(TAG, "Found preview size exactly matching screen size: " + exactPoint);
            return exactPoint;
        }
    }

    // If no exact match, use largest preview size. This was not a great idea on older devices because
    // of the additional computation needed. We're likely to get here on newer Android 4+ devices, where
    // the CPU is much more powerful.
    if (!supportedPreviewSizes.isEmpty()) {
        Size largestPreview = supportedPreviewSizes.get(0);
        Point largestSize = new Point(largestPreview.width, largestPreview.height);
        Log.i(TAG, "Using largest suitable preview size: " + largestSize);
        return largestSize;
    }

    // If there is nothing at all suitable, return current preview size
    Size defaultPreview = parameters.getPreviewSize();
    if (defaultPreview == null) {
        throw new IllegalStateException("Parameters contained no preview size!");
    }
    Point defaultSize = new Point(defaultPreview.width, defaultPreview.height);
    Log.i(TAG, "No suitable preview sizes, using default: " + defaultSize);
    return defaultSize;
}

From source file:com.netflix.nicobar.core.utils.ClassPathUtils.java

private static Set<String> filterPathSet(Set<String> pathSet, Set<String> excludePrefixes,
        Set<String> includePrefixes) {
    Set<String> filteredSet = new HashSet<String>(pathSet);

    // Ideally, we would use a trie, but we are talking ~100s of paths and a few excludes and includes,
    // not to mention these are throw away scans and not reused typically.

    // First process the excludes
    for (String exclude : excludePrefixes) {
        Iterator<String> setIterator = filteredSet.iterator();
        while (setIterator.hasNext()) {
            String path = setIterator.next();
            if (path.startsWith(exclude))
                setIterator.remove();
        }//from www . j ava2s .  c o  m
    }

    // An empty set of includes indicates include everything
    if (includePrefixes.size() == 0) {
        return filteredSet;
    }

    // Now, create a filtered set based on the includes
    Iterator<String> setIterator = filteredSet.iterator();
    while (setIterator.hasNext()) {
        String path = setIterator.next();
        boolean shouldInclude = false;
        for (String include : includePrefixes) {
            if (path.startsWith(include)) {
                shouldInclude = true;
                break;
            }
        }

        // Remove if none of the includes specify this package path
        if (!shouldInclude) {
            setIterator.remove();
        }
    }

    return filteredSet;
}