Example usage for java.util Collection remove

List of usage examples for java.util Collection remove

Introduction

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

Prototype

boolean remove(Object o);

Source Link

Document

Removes a single instance of the specified element from this collection, if it is present (optional operation).

Usage

From source file:uk.ac.ebi.intact.editor.controller.curate.AnnotatedObjectController.java

public void removeAnnotation(String topic, String topicMI, String value, Collection<Annotation> annots) {
    if (topic == null) {
        throw new IllegalArgumentException(
                "Impossible to replace or create annotations if the topic is not set.");
    }// w  w w.ja  v a  2s .c  o  m

    // modify if exists
    Collection<Annotation> existingAnnots = AnnotationUtils.collectAllAnnotationsHavingTopic(annots, topicMI,
            topic);
    for (Annotation ann : existingAnnots) {
        if (value == null && ann.getValue() == null) {
            annots.remove(ann);
        } else if (value != null && value.equals(ann.getValue())) {
            annots.remove(ann);
        }
    }
    setUnsavedChanges(true);
}

From source file:org.opencms.notification.CmsNotificationCandidates.java

/**
 * Updates the resources that were confirmed by the user. That means deletes the resources that need not a
 * notification any more./*from www .j  a va 2  s.  c  o m*/
 * removes all resources which do not occur in the candidate list.<p>
 * 
 * @param contentNotifications the list of {@link CmsContentNotification} objects to remove from the set of confirmed resources
 * @return a new CmsConfirmedResources Object which all the resource removed
 */
private Collection filterConfirmedResources(Collection contentNotifications) {

    Iterator notifications = contentNotifications.iterator();
    while (notifications.hasNext()) {
        CmsContentNotification contentNotification = (CmsContentNotification) notifications.next();
        CmsUser responsible = contentNotification.getResponsible();
        // check, if user was already notified
        List confirmedResourcesList = (List) responsible
                .getAdditionalInfo(CmsUserSettings.ADDITIONAL_INFO_CONFIRMED_RESOURCES);
        if (confirmedResourcesList == null) {
            confirmedResourcesList = new ArrayList();
            responsible.setAdditionalInfo(CmsUserSettings.ADDITIONAL_INFO_CONFIRMED_RESOURCES, new ArrayList());
        }

        List notificationCandidates = contentNotification.getNotificationCauses();

        List notificationResources = new ArrayList(notificationCandidates);
        // remove already confirmed resources            
        Iterator i = confirmedResourcesList.iterator();
        while (i.hasNext()) {
            Object o = i.next();
            if (notificationResources.contains(o)) {
                notificationResources.remove(o);
            }
        }
        // filter confirmed resources
        i = new ArrayList(confirmedResourcesList).iterator();
        while (i.hasNext()) {
            Object o = i.next();
            if (!notificationCandidates.contains(o)) {
                confirmedResourcesList.remove(o);
            }
        }
        contentNotification.setNotificationCauses(notificationResources);
        // Remove notification, if resource list is empty
        if (notificationCandidates.isEmpty()) {
            contentNotifications.remove(contentNotification);
        }
        try {
            m_cms.writeUser(responsible);
        } catch (CmsException e) {
            LOG.error(e.getLocalizedMessage(), e);
        }
    }
    return contentNotifications;
}

From source file:com.wavemaker.tools.data.DataModelConfiguration.java

public boolean compareTo(DataModelConfiguration other) {
    Collection<String> c = new HashSet<String>(getEntityNames());
    for (String s : other.getEntityNames()) {
        if (!c.remove(s)) {
            return false;
        }//from w ww  .j  a  va 2  s.  c o m
    }
    if (!c.isEmpty()) {
        return false;
    }
    return true;
}

From source file:playground.johannes.socialnets.NetworkGenerator2.java

private Collection<Ego> closeTriads(Collection<Ego> currentWave, TObjectIntHashMap<Ego> stubsMap,
        Collection<Ego> pendingNodes, SocialNetwork net) {
    Collection<Ego> nextWave = new HashSet<Ego>();

    for (Ego v1 : currentWave) {
        Set<Ego> potentialTriads = new HashSet<Ego>();
        if (stubsMap.get(v1) > 0)
            potentialTriads.add(v1);//ww w  .  j a  v  a2s .co  m

        for (Vertex n1 : v1.getNeighbours()) {
            for (Vertex n2 : n1.getNeighbours()) {
                if (n2 != v1) {
                    if (stubsMap.get((Ego) n2) > 0)
                        potentialTriads.add((Ego) n2);
                }
            }
        }

        for (Ego v2 : potentialTriads) {
            int stubs = stubsMap.get(v2);
            //            System.err.println("Num stubs before = " + stubs);
            //            boolean formedConnection = false;
            for (int i = 0; i < stubs; i++) {
                List<Ego> potentialTriads2 = new LinkedList<Ego>(potentialTriads);
                Collections.shuffle(potentialTriads2);

                for (Ego v3 : potentialTriads2) {
                    if (v2 != v3) {
                        /*
                         * For now, constant clustering
                         */
                        double p = getDyadProba(v2, v3, scale3);
                        if (random.nextDouble() <= p) {

                            if (formConnection(v2, v3, net, stubsMap)) {
                                //                           formedConnection = true;

                                if (stubsMap.get(v2) == 0)
                                    pendingNodes.remove(v2);
                                if (stubsMap.get(v3) == 0)
                                    pendingNodes.remove(v3);

                                break;
                            }
                        }
                    }
                }
            }

            if (stubsMap.get(v2) > 0) {
                Ego v3 = findNeighbour(v2, egoList, stubsMap, true);
                if (v3 == null) {
                    /*
                     * TODO: This is tricky! Obviously there are no nodes
                     * with open stubs left!
                     */
                    System.err.println("Aborted triad closure. No stubs are left!");
                    return nextWave;
                }
                if (formConnection(v2, v3, net, stubsMap)) {
                    if (!currentWave.contains(v3))
                        nextWave.add(v3);

                    if (stubsMap.get(v2) == 0)
                        pendingNodes.remove(v2);
                    if (stubsMap.get(v3) == 0)
                        pendingNodes.remove(v3);
                } else {
                    int v2stubs = stubsMap.get(v2);
                    int v3stubs = stubsMap.get(v3);
                    System.err.println("The selected neighbour is not valid!" + " v2stubs=" + v2stubs
                            + ", v3stubs=" + v3stubs);
                    System.exit(-1);
                }
            }

            //            if (stubs - (i + 1) != stubsMap.get(v2)) {
            //               System.err.println("Stub not connected!");
            //            }
            //
            //            // System.err.println("Num stubs after = " + stubsMap.get(v1));
            //            if (stubsMap.get(v2) != 0) {
            //               System.err.println("Vertex has stubs left!");
            //            }
        }
    }

    //      if(nextWave.isEmpty()) {
    //         int triadstubs = 0;
    //         for(Ego v : potentialTriads)
    //            triadstubs += stubsMap.get(v);
    //         System.err.println("Triad stubs = " + triadstubs);
    //         
    //         int totalstubs = 0;
    //         for(Ego v : egoList)
    //            totalstubs += stubsMap.get(v);
    //         System.err.println("Total stubs = " + totalstubs);
    //      }
    return nextWave;
}

From source file:de.juwimm.cms.remote.UserServiceSpringImpl.java

/**
 * @see de.juwimm.cms.remote.UserServiceSpring#setConnectedUsers4Site(java.lang.Integer,
 *      java.lang.String[])//from  w w  w .j ava2 s.  c o  m
 */
@Override
protected void handleSetConnectedUsers4Site(Integer siteId, String[] userIds) throws Exception {
    Collection<UserHbm> usersIn = null;
    Collection<String> usersRemove = new ArrayList<String>();
    Collection<String> users = new ArrayList<String>();

    // Collections are nicer to handle
    for (int i = 0; i < userIds.length; i++) {
        users.add(userIds[i]);
    }

    SiteHbm site = null;
    try {
        site = super.getSiteHbmDao().load(siteId);
        usersIn = site.getUsers();

    } catch (Exception exe) {
        log.warn("Error while executing the finder \"findAll\" in getConnectedUsersForSite: "
                + exe.getMessage());
    }

    // compare old user list with new one -> element in both means stay,
    // just in old means del
    for (UserHbm user : usersIn) {
        if (users.contains(user.getUserId())) {
            users.remove(user.getUserId());
        } else {
            usersRemove.add(user.getUserId());
        }
    }

    // users still in list are the really new ones - create them
    for (String userId : users) {
        UserHbm user = super.getUserHbmDao().load(userId);
        user.getSites().add(site);
    }

    // remove the users deleted users
    for (String userId : usersRemove) {
        UserHbm user = super.getUserHbmDao().load(userId);
        user.getSites().remove(site);
    }
}

From source file:com.silverpeas.gallery.servlets.GalleryRequestRouter.java

/**
 * update gallery session controller list of selected elements
 * @param request/*w ww  . j a v a2  s  .c om*/
 * @param gallerySC
 */
private void processSelection(HttpServletRequest request, GallerySessionController gallerySC) {
    String selectedIds = request.getParameter("SelectedIds");
    String notSelectedIds = request.getParameter("NotSelectedIds");
    Collection<String> memSelected = gallerySC.getListSelected();

    if (StringUtil.isDefined(selectedIds)) {
        for (String selectedId : selectedIds.split(",")) {
            if (!memSelected.contains(selectedId)) {
                memSelected.add(selectedId);
            }
        }
    }

    if (StringUtil.isDefined(notSelectedIds)) {
        for (String notSelectedId : notSelectedIds.split(",")) {
            memSelected.remove(notSelectedId);
        }
    }
}

From source file:net.sf.morph.context.support.ContextBaseTestCase.java

public void testKeySet() {

    Set keySet = null;/*from   w  w  w.j  a v a 2s . co m*/
    Collection all = new ArrayList();

    // Unsupported operations
    //        keySet = context.keySet();
    //        try {
    //            keySet.add("bop");
    //            fail("Should have thrown UnsupportedOperationException");
    //        } catch (UnsupportedOperationException e) {
    //            ; // Expected result
    //        }
    //        try {
    //            Collection adds = new ArrayList();
    //            adds.add("bop");
    //            keySet.addAll(adds);
    //            fail("Should have thrown UnsupportedOperationException");
    //        } catch (UnsupportedOperationException e) {
    //            ; // Expected result
    //        }

    // Before-modification checks
    keySet = context.keySet();
    assertEquals(context.size(), keySet.size());
    assertTrue(!keySet.contains("foo"));
    assertTrue(!keySet.contains("bar"));
    assertTrue(!keySet.contains("baz"));
    assertTrue(!keySet.contains("bop"));

    // Add the new elements
    context.put("foo", "foo value");
    context.put("bar", "bar value");
    context.put("baz", "baz value");
    all.add("foo");
    all.add("bar");
    all.add("baz");

    // After-modification checks
    keySet = context.keySet();
    assertEquals(expectedAttributeCount() + 3, keySet.size());
    assertTrue(keySet.contains("foo"));
    assertTrue(keySet.contains("bar"));
    assertTrue(keySet.contains("baz"));
    assertTrue(!keySet.contains("bop"));
    assertTrue(keySet.containsAll(all));

    // Remove a single element via remove()
    //        context.remove("bar");
    all.remove("bar");
    keySet = context.keySet();
    assertEquals(expectedAttributeCount() + 3, keySet.size());
    assertTrue(keySet.contains("foo"));
    //        assertTrue(!keySet.contains("bar"));
    assertTrue(keySet.contains("baz"));
    assertTrue(!keySet.contains("bop"));
    assertTrue(keySet.containsAll(all));

    // Remove a single element via keySet.remove()
    keySet.remove("baz");
    all.remove("baz");
    keySet = context.keySet();
    assertEquals(expectedAttributeCount() + 3, keySet.size());
    assertTrue(keySet.contains("foo"));
    //        assertTrue(!keySet.contains("bar"));
    //        assertTrue(!keySet.contains("baz"));
    assertTrue(!keySet.contains("bop"));
    assertTrue(keySet.containsAll(all));

    // Remove all elements via keySet.clear()
    all.clear();
    //        assertTrue(!keySet.contains("foo"));
    //        assertTrue(!keySet.contains("bar"));
    //        assertTrue(!keySet.contains("baz"));
    assertTrue(!keySet.contains("bop"));
    assertTrue(keySet.containsAll(all));

    // Add the new elements #2
    context.put("foo", "foo value");
    context.put("bar", "bar value");
    context.put("baz", "baz value");
    all.add("foo");
    all.add("bar");
    all.add("baz");

    // After-modification checks #2
    keySet = context.keySet();
    assertEquals(expectedAttributeCount() + 3, keySet.size());
    assertTrue(keySet.contains("foo"));
    assertTrue(keySet.contains("bar"));
    assertTrue(keySet.contains("baz"));
    assertTrue(!keySet.contains("bop"));
    assertTrue(keySet.containsAll(all));

}

From source file:org.onosproject.drivers.juniper.FlowRuleJuniperImpl.java

@Override
public Collection<FlowEntry> getFlowEntries() {

    DeviceId devId = checkNotNull(this.data().deviceId());
    NetconfController controller = checkNotNull(handler().get(NetconfController.class));
    NetconfSession session = controller.getDevicesMap().get(devId).getSession();
    if (session == null) {
        log.warn("Device {} is not registered in netconf", devId);
        return Collections.EMPTY_LIST;
    }//from ww  w.j  a v a2  s.  com

    //Installed static routes
    String reply;
    try {
        reply = session.get(routingTableBuilder());
    } catch (NetconfException e) {
        throw new IllegalStateException(new NetconfException("Failed to retrieve configuration.", e));
    }
    Collection<StaticRoute> devicesStaticRoutes = JuniperUtils.parseRoutingTable(loadXmlString(reply));

    //Expected FlowEntries installed
    FlowRuleService flowRuleService = this.handler().get(FlowRuleService.class);
    Iterable<FlowEntry> flowEntries = flowRuleService.getFlowEntries(devId);

    Collection<FlowEntry> installedRules = new HashSet<>();
    flowEntries.forEach(flowEntry -> {
        Optional<IPCriterion> ipCriterion = getIpCriterion(flowEntry);
        if (!ipCriterion.isPresent()) {
            return;
        }

        Optional<OutputInstruction> output = getOutput(flowEntry);
        if (!output.isPresent()) {
            return;
        }
        //convert FlowRule into static route
        getStaticRoute(devId, ipCriterion.get(), output.get(), flowEntry.priority()).ifPresent(staticRoute -> {
            //Two type of FlowRules:
            //1. FlowRules to forward to a remote subnet: they are translated into static route
            // configuration. So a removal request will be processed.
            //2. FlowRules to forward on a subnet directly attached to the router (Generally speaking called local):
            // those routes do not require any configuration because the router is already able to forward on
            // directly attached subnet. In this case, when the driver receive the request to remove,
            // it will report as removed.

            if (staticRoute.isLocalRoute()) {
                //if the FlowRule is in PENDING_REMOVE or REMOVED, it is not reported.
                if (flowEntry.state() == PENDING_REMOVE || flowEntry.state() == REMOVED) {
                    devicesStaticRoutes.remove(staticRoute);
                } else {
                    //FlowRule is reported installed
                    installedRules.add(flowEntry);
                    devicesStaticRoutes.remove(staticRoute);
                }

            } else {
                //if the route is found in the device, the FlowRule is reported installed.
                if (devicesStaticRoutes.contains(staticRoute)) {
                    installedRules.add(flowEntry);
                    devicesStaticRoutes.remove(staticRoute);
                }
            }
        });
    });

    if (!devicesStaticRoutes.isEmpty()) {
        log.info("Found static routes on device {} not installed by ONOS: {}", devId, devicesStaticRoutes);
        //            FIXME: enable configuration to purge already installed flows.
        //            It cannot be allowed by default because it may remove needed management routes
        //            log.warn("Removing from device {} the FlowEntries not expected {}", deviceId, devicesStaticRoutes);
        //            devicesStaticRoutes.forEach(staticRoute -> editRoute(session, REMOVE, staticRoute));
    }
    return installedRules;
}

From source file:uk.nhs.cfh.dsp.snomed.normaliser.impl.NormalFormGeneratorImpl.java

/**
 * Gets the strict non redundant merged relationships.
 *
 * @param parentPropertyExpressions the parent property expressions
 * @param conceptPropertyExpressions the concept property expressions
 * @return the strict non redundant merged relationships
 *//*from w w  w  .j av  a 2  s.  com*/
private Collection<SnomedRelationshipPropertyExpression> getStrictNonRedundantMergedRelationships(
        Collection<SnomedRelationshipPropertyExpression> parentPropertyExpressions,
        Collection<SnomedRelationshipPropertyExpression> conceptPropertyExpressions) {
    if (parentPropertyExpressions.size() == 0) {
        return conceptPropertyExpressions;
    } else if (conceptPropertyExpressions.size() == 0) {
        return parentPropertyExpressions;
    } else {
        Collection<SnomedRelationshipPropertyExpression> relationshipPropertyExpressionCopy = new ArrayList<SnomedRelationshipPropertyExpression>(
                conceptPropertyExpressions);
        for (SnomedRelationshipPropertyExpression parentExpression : parentPropertyExpressions) {
            for (SnomedRelationshipPropertyExpression conceptPropertyExpression : relationshipPropertyExpressionCopy) {
                ExpressionComparator.Subsumption_Relation relation = expressionComparator
                        .getSubsumptionRelation(parentExpression, conceptPropertyExpression);
                if (ExpressionComparator.Subsumption_Relation.SAME == relation
                        || ExpressionComparator.Subsumption_Relation.SUBSUMES == relation) {
                    conceptPropertyExpressions.remove(conceptPropertyExpression);
                }
            }
        }

        return conceptPropertyExpressions;
    }
}

From source file:org.openmrs.util.OpenmrsUtil.java

/**
 * Compares origList to newList returning map of differences
 * /*from ww  w  .ja v a  2 s  . c  o  m*/
 * @param origList
 * @param newList
 * @return [List toAdd, List toDelete] with respect to origList
 */
public static <E extends Object> Collection<Collection<E>> compareLists(Collection<E> origList,
        Collection<E> newList) {
    // TODO finish function

    Collection<Collection<E>> returnList = new Vector<Collection<E>>();

    Collection<E> toAdd = new LinkedList<E>();
    Collection<E> toDel = new LinkedList<E>();

    // loop over the new list.
    for (E currentNewListObj : newList) {
        // loop over the original list
        boolean foundInList = false;
        for (E currentOrigListObj : origList) {
            // checking if the current new list object is in the original
            // list
            if (currentNewListObj.equals(currentOrigListObj)) {
                foundInList = true;
                origList.remove(currentOrigListObj);
                break;
            }
        }
        if (!foundInList) {
            toAdd.add(currentNewListObj);
        }

        // all found new objects were removed from the orig list,
        // leaving only objects needing to be removed
        toDel = origList;

    }

    returnList.add(toAdd);
    returnList.add(toDel);

    return returnList;
}