Example usage for java.util ArrayList retainAll

List of usage examples for java.util ArrayList retainAll

Introduction

In this page you can find the example usage for java.util ArrayList retainAll.

Prototype

public boolean retainAll(Collection<?> c) 

Source Link

Document

Retains only the elements in this list that are contained in the specified collection.

Usage

From source file:Main.java

public static void main(String args[]) {
    ArrayList<Integer> arrlist = new ArrayList<Integer>();

    arrlist.add(1);//ww  w  .j av a  2  s  .  c o  m
    arrlist.add(2);
    arrlist.add(3);
    arrlist.add(4);
    arrlist.add(5);

    ArrayList<Integer> arrlist2 = new ArrayList<Integer>();
    arrlist2.add(1);
    arrlist2.add(2);
    arrlist2.add(3);

    arrlist.retainAll(arrlist2);

    System.out.println(arrlist);

}

From source file:Main.java

public static int countCommElmts(ArrayList<String> u, ArrayList<String> v) {
    ArrayList<String> listOne = new ArrayList<String>();
    listOne.addAll(u);/*from www .j  av  a2  s  . co  m*/
    listOne.retainAll(v);
    return listOne.size();
}

From source file:Main.java

public static int countDiffElmts(ArrayList<String> u, ArrayList<String> v) {
    ArrayList<String> listOne = new ArrayList<String>();
    ArrayList<String> listTwo = new ArrayList<String>();
    listOne.addAll(u);/*from   w  ww.j  av a  2  s  .c o m*/
    listOne.retainAll(v);
    listTwo.addAll(u);
    listTwo.addAll(v);
    listTwo.removeAll(listOne);
    return listTwo.size();
}

From source file:Main.java

public static ArrayList<Integer> intersection(ArrayList<Integer> arrayList1, ArrayList<Integer> arrayList2) {
    ArrayList<Integer> intersectionList = new ArrayList<Integer>(
            arrayList1.size() > arrayList2.size() ? arrayList1.size() : arrayList2.size());
    intersectionList.addAll(arrayList1);
    intersectionList.retainAll(arrayList2);
    return intersectionList;
}

From source file:org.apache.accumulo.server.fs.PreferredVolumeChooser.java

@Override
public String choose(VolumeChooserEnvironment env, String[] options) {
    if (!env.hasTableId())
        return super.choose(env, options);

    // Get the current table's properties, and find the preferred volumes property
    // This local variable is an intentional component of the single-check idiom.
    ServerConfigurationFactory localConf = serverConfs;
    if (localConf == null) {
        // If we're under contention when first getting here we'll throw away some initializations.
        localConf = new ServerConfigurationFactory(HdfsZooInstance.getInstance());
        serverConfs = localConf;//from  ww w . j a v a 2 s  .  com
    }
    TableConfiguration tableConf = localConf.getTableConfiguration(env.getTableId());
    final Map<String, String> props = new HashMap<String, String>();
    tableConf.getProperties(props, PREFERRED_VOLUMES_FILTER);
    if (props.isEmpty()) {
        log.warn("No preferred volumes specified. Defaulting to randomly choosing from instance volumes");
        return super.choose(env, options);
    }
    String volumes = props.get(PREFERRED_VOLUMES_CUSTOM_KEY);

    if (log.isTraceEnabled()) {
        log.trace("In custom chooser");
        log.trace("Volumes: " + volumes);
        log.trace("TableID: " + env.getTableId());
    }
    // If the preferred volumes property was specified, split the returned string by the comma and add use it to filter the given options.
    Set<String> preferred = parsedPreferredVolumes.get(volumes);
    if (preferred == null) {
        preferred = new HashSet<String>(Arrays.asList(StringUtils.split(volumes, ',')));
        parsedPreferredVolumes.put(volumes, preferred);
    }

    // Only keep the options that are in the preferred set
    final ArrayList<String> filteredOptions = new ArrayList<String>(Arrays.asList(options));
    filteredOptions.retainAll(preferred);

    // If there are no preferred volumes left, then warn the user and choose randomly from the instance volumes
    if (filteredOptions.isEmpty()) {
        log.warn(
                "Preferred volumes are not instance volumes. Defaulting to randomly choosing from instance volumes");
        return super.choose(env, options);
    }

    // Randomly choose the volume from the preferred volumes
    String choice = super.choose(env, filteredOptions.toArray(EMPTY_STRING_ARRAY));
    if (log.isTraceEnabled()) {
        log.trace("Choice = " + choice);
    }
    return choice;
}

From source file:net.i2cat.netconf.test.BaseNetconfTest.java

@Test
public void testCapabilities() {

    ArrayList<Capability> activeCapabilities = session.getActiveCapabilities();
    ArrayList<Capability> clientCapabilities = session.getClientCapabilities();
    ArrayList<Capability> serverCapabilities = session.getServerCapabilities();

    assertTrue("Base capability must be supported and active", activeCapabilities.contains(Capability.BASE));
    assertTrue("There is an active capability that we don't support",
            clientCapabilities.containsAll(activeCapabilities));
    assertTrue("There is an active capability that the server doesn't support",
            serverCapabilities.containsAll(activeCapabilities));

    ArrayList<Capability> commonCapabilities = new ArrayList<Capability>(clientCapabilities);
    commonCapabilities.retainAll(serverCapabilities);

    assertTrue("Active capabilities equal common client/server capabilities",
            commonCapabilities.containsAll(activeCapabilities)
                    && activeCapabilities.containsAll(commonCapabilities));
}

From source file:model.DrawTopologyDiagram.java

public boolean testCaseSelected(TestCase testCase, ArrayList<String> endPointList) {
    //Make a clone to make changes    
    List<ArrayList<String>> inputDeviceList = new ArrayList<ArrayList<String>>(
            testCase.getInputDeviceList().size());
    for (ArrayList<String> p : testCase.getInputDeviceList()) {
        ArrayList<String> tempList = new ArrayList<String>(p.size());
        for (String endPointTemp : tempList)
            p.add(endPointTemp);/*from   w  w  w .  j a  v a 2s. co  m*/
        inputDeviceList.add(p);
    }

    List<String> endPointListTemp = new ArrayList<String>(endPointList.size());
    for (String temp : endPointList)
        endPointListTemp.add(temp);

    //first filter out relevant endpoints
    for (ArrayList<String> inputDeviceListTemp : inputDeviceList) {
        inputDeviceListTemp.retainAll(endPointListTemp);

    }
    //sort with lowest first
    Collections.sort(inputDeviceList, new Comparator<ArrayList>() {
        public int compare(ArrayList a1, ArrayList a2) {
            return a1.size() - a2.size(); // assumes you want biggest to smallest
        }
    });
    // remove similar
    int similarCount = 0;
    for (int i = 0; i < inputDeviceList.size(); i++) {
        if (endPointListTemp.size() < 1)
            break;
        for (String temp : inputDeviceList.get(i)) {
            if (endPointListTemp.size() > 0) {
                if (endPointListTemp.contains(temp)) {
                    endPointListTemp.remove(temp);
                    similarCount++;
                    break;
                }
            }
        }
    }
    if (similarCount == testCase.getInputDeviceList().size())
        return true;
    else
        return false;
}

From source file:net.i2cat.netconf.transport.MockTransport.java

public void sendAsyncQuery(RPCElement elem) throws TransportException {

    Reply reply = new Reply();
    Vector<Error> errors = new Vector<Error>();

    if (elem instanceof Hello) {

        // Capability b
        ArrayList<Capability> capabilities = ((Hello) elem).getCapabilities();
        capabilities.retainAll(this.supportedCapabilities);
        context.setActiveCapabilities(capabilities);

    }// ww  w  . ja v a 2  s .  c  o  m
    if (elem instanceof Query) {
        Query query = (Query) elem;
        Operation op = query.getOperation();

        if (op.equals(Operation.COPY_CONFIG)) {
        } else if (op.equals(Operation.DELETE_CONFIG)) {
            reply.setOk(true);
            reply.setMessageId(query.getMessageId());
        } else if (op.equals(Operation.EDIT_CONFIG)) {
            reply.setOk(true);
            reply.setMessageId(query.getMessageId());
        } else if (op.equals(Operation.GET)) {

            if (query.getFilter() != null && query.getFilterType() != null) {
                if (context.getActiveCapabilities().contains(Capability.XPATH)) {
                    if (!(query.getFilterType().equals("xpath") || query.getFilterType().equals("subtree")))
                        errors.add(new Error() {
                            {
                                setTag(ErrorTag.BAD_ATTRIBUTE);
                                setType(ErrorType.PROTOCOL);
                                setSeverity(ErrorSeverity.ERROR);
                                setInfo("<bad-attribute> : Wrong filter type. Neither xpath nor subtree.");
                            }
                        });
                    else if (query.getFilterType().equals("subtree"))
                        errors.add(new Error() {
                            {
                                setTag(ErrorTag.BAD_ATTRIBUTE);
                                setType(ErrorType.PROTOCOL);
                                setSeverity(ErrorSeverity.ERROR);
                                setInfo("<bad-attribute> : Wrong filter type. Not subtree.");
                            }
                        });
                }
            }
            reply.setMessageId(query.getMessageId());

            reply.setContain(getDataFromFile(fileIPConfiguration));

        } else if (op.equals(Operation.GET_CONFIG)) {
            // it is not include any get config, it is an error
            if (query.getSource() == null)
                errors.add(new Error() {
                    {
                        setTag(ErrorTag.MISSING_ELEMENT);
                        setType(ErrorType.PROTOCOL);
                        setSeverity(ErrorSeverity.ERROR);
                        setInfo("<bad-element> : No source configuration specified");
                    }
                });
            if (query.getFilter() != null && query.getFilterType() != null) {
                if (context.getActiveCapabilities().contains(Capability.XPATH)) {
                    if (!(query.getFilterType().equals("xpath") || query.getFilterType().equals("subtree")))
                        errors.add(new Error() {
                            {
                                setTag(ErrorTag.BAD_ATTRIBUTE);
                                setType(ErrorType.PROTOCOL);
                                setSeverity(ErrorSeverity.ERROR);
                                setInfo("<bad-attribute> : Wrong filter type. Neither xpath nor subtree.");
                            }
                        });
                    else if (query.getFilterType().equals("subtree"))
                        errors.add(new Error() {
                            {
                                setTag(ErrorTag.BAD_ATTRIBUTE);
                                setType(ErrorType.PROTOCOL);
                                setSeverity(ErrorSeverity.ERROR);
                                setInfo("<bad-attribute> : Wrong filter type. Not subtree.");
                            }
                        });
                }
            }

            reply.setMessageId(query.getMessageId());
            if (logicalRouterName == null) {
                reply.setContain(getDataFromFile(fileIPConfiguration));
            } else {

                String path = createPathFileLogicalRouter(logicalRouterName);
                reply.setContain(getDataFromFile(path));
            }

        } else if (op.equals(Operation.KILL_SESSION)) {
            logicalRouterName = null;
            disconnect();
            return;
        } else if (op.equals(Operation.CLOSE_SESSION)) {
            reply.setMessageId(query.getMessageId());
            reply.setOk(true);
            logicalRouterName = null;
            disconnect();
        } // FIXME ADD ELSE IF FOR ROLLBACK
        /* include junos capabilities operations */
        else if (op.equals(Operation.SET_LOGICAL_ROUTER)) {
            reply.setMessageId(query.getMessageId());
            reply.setContain("<cli><logical-system>" + query.getIdLogicalRouter() + "</logical-system></cli>");
            logicalRouterName = query.getIdLogicalRouter();

        } else if (op.equals(Operation.GET_INTERFACE_INFO)) {
            reply.setMessageId(query.getMessageId());
            reply.setContainName("information-information");
            reply.setContain(getDataFromFile(fileShowInterfaceInformation));
        } else if (op.equals(Operation.GET_ROUTE_INFO)) {
            reply.setMessageId(query.getMessageId());
            reply.setContainName("route-information");
            reply.setContain(getDataFromFile(fileShowRouteInformation));

        } else if (op.equals(Operation.GET_ROLLBACK_INFO)) {
            reply.setMessageId(query.getMessageId());
            reply.setContainName("rollback-information");
            reply.setContain(getDataFromFile(fileShowRollbackInformation));

        } else if (op.equals(Operation.GET_SOFTWARE_INFO)) {
            reply.setMessageId(query.getMessageId());
            reply.setContainName("software-information");
            reply.setContain(getDataFromFile(fileShowSoftwareInformation));

        } else if (op.equals(Operation.COMMIT) || op.equals(Operation.DISCARD) || op.equals(Operation.VALIDATE)
                || op.equals(Operation.LOCK) || op.equals(Operation.UNLOCK)) {
            reply.setMessageId(query.getMessageId());
            reply.setOk(true);
        }

    }

    // force to add errors in the response message
    if (subsystem.equals("errorServer"))
        addErrors(errors);

    if (errors.size() > 0)
        reply.setErrors(errors);

    queue.put(reply);
}

From source file:com.espertech.esper.core.context.mgr.ContextManagerNested.java

private Collection<Integer> getAgentInstancesForSelector(ContextPartitionSelector selector) {
    if (selector instanceof ContextPartitionSelectorById) {
        ContextPartitionSelectorById byId = (ContextPartitionSelectorById) selector;
        Set<Integer> ids = byId.getContextPartitionIds();
        if (ids == null || ids.isEmpty()) {
            return Collections.emptyList();
        }//  w  ww .j  a  v a  2 s .co  m
        ArrayList agentInstanceIds = new ArrayList<Integer>(ids);
        agentInstanceIds.retainAll(contextPartitionIdManager.getIds());
        return agentInstanceIds;
    } else if (selector instanceof ContextPartitionSelectorAll) {
        return new ArrayList<Integer>(contextPartitionIdManager.getIds());
    } else if (selector instanceof ContextPartitionSelectorNested) {
        ContextPartitionSelectorNested nested = (ContextPartitionSelectorNested) selector;
        ContextPartitionVisitorAgentInstanceIdWPath visitor = new ContextPartitionVisitorAgentInstanceIdWPath(
                nestedContextFactories.length);
        for (ContextPartitionSelector[] item : nested.getSelectors()) {
            recursivePopulateSelector(rootContext, 1, item, visitor);
        }
        return visitor.getAgentInstanceIds();
    }
    throw ContextControllerSelectorUtil.getInvalidSelector(new Class[] { ContextPartitionSelectorNested.class },
            selector, true);
}

From source file:com.ntua.cosmos.hackathonplanneraas.Planner.java

/**
 * /*  w  w  w  .  ja v a 2s  .  co  m*/
 * @param params
 * @param thr
 * @return 
 */
public boolean compareProbParams(ArrayList<String> params, double thr) {
    //query for all problem ATTRIBUTES of each problem in localstore.        
    System.out.println("***************************************");
    System.out.println(
            "At this point we are checking if a similar problem " + "structure is present in the Case Base.");
    System.out.println("***************************************\n\n");
    StoredPaths pan = new StoredPaths();
    boolean isworthchecking = false;
    double similarity;
    ArrayList<ArrayList<String>> contents = new ArrayList<>();
    ArrayList<String> tempparam = new ArrayList<>();
    ArrayList<String> namelist = new ArrayList<>();
    String tempname = "";
    for (int i = 0; i < params.size(); i++) {
        String tempName = params.get(i);
        if (tempName.equals("ttl")) {
            params.remove(i);
        }
    }
    //Begin the initialisation process.
    OntModelSpec s = new OntModelSpec(OntModelSpec.OWL_DL_MEM);
    OntDocumentManager dm = OntDocumentManager.getInstance();
    dm.setFileManager(FileManager.get());
    s.setDocumentManager(dm);
    OntModel m = ModelFactory.createOntologyModel(s, null);
    InputStream in = FileManager.get().open(StoredPaths.casebasepath);
    if (in == null) {
        throw new IllegalArgumentException("File: " + StoredPaths.casebasepath + " not found");
    }
    // read the file
    m.read(in, null);
    //begin building query string.
    String queryString = pan.prefixrdf + pan.prefixowl + pan.prefixxsd + pan.prefixrdfs + pan.prefixCasePath;
    queryString += "\nSELECT distinct ?prob ?param WHERE { ?prob ?param ?value . ?prob base:hasCaseType \"problem\"^^xsd:string . filter isLiteral(?value) . ?param a owl:DatatypeProperty . filter not exists{  { filter regex(str(?value), \"problem\" )} union {?prob ?param true} union {?prob ?param false} } }";
    System.out.println("***************************************");
    System.out.println("Query String used: ");
    System.out.println(queryString);
    System.out.println("***************************************\n\n");
    try {
        Query query = QueryFactory.create(queryString);
        QueryExecution qe = QueryExecutionFactory.create(query, m);
        ResultSet results = qe.execSelect();
        int i = 0;
        for (; results.hasNext();) {
            QuerySolution soln = results.nextSolution();
            // Access variables: soln.get("x");
            Resource res;
            Resource res2;
            res = soln.getResource("prob");// Get a result variable by name.
            if (!res.getURI().equalsIgnoreCase(tempname)) {
                tempname = res.getURI();
                namelist.add(res.getURI());
                i++;
                if (!tempparam.isEmpty())
                    contents.add(new ArrayList<>(tempparam));
                tempparam.clear();
            }
            res2 = soln.getResource("param");
            tempparam.add(res2.getURI().substring(res2.getURI().indexOf('#') + 1));
        }
        qe.close();
        contents.add(new ArrayList<>(tempparam));
    } catch (NumberFormatException e) {
        System.out.println("Query not valid.");
    }
    m.close();
    ArrayList<String> union = new ArrayList<>();
    ArrayList<String> intersection = new ArrayList<>();
    int i = 0;
    for (ArrayList<String> content : contents) {
        intersection.addAll(params);
        intersection.retainAll(content);
        union.addAll(content);
        similarity = intersection.size() / union.size();
        if (similarity >= thr) {
            isworthchecking = true;
            System.out.println("The Case is worth checking because of this " + similarity + " metric "
                    + "in problem identified as " + namelist.get(i) + ".");
        }
        i++;
        intersection.clear();
        union.clear();
    }
    return isworthchecking;
}