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:it.iit.genomics.cru.igb.bundles.mi.business.MIResult.java

public String getDiseasesHtml() {
    Collection<String> diseasesA = container1.getEntry().getDiseases();
    Collection<String> diseasesB = container2.getEntry().getDiseases();
    ArrayList<String> commonDiseases = new ArrayList<>();
    ArrayList<String> uniqueDiseasesA = new ArrayList<>();
    ArrayList<String> uniqueDiseasesB = new ArrayList<>();

    commonDiseases.addAll(diseasesA);/* w ww  . j av  a 2s  . co  m*/
    commonDiseases.retainAll(diseasesB);

    uniqueDiseasesA.addAll(diseasesA);
    uniqueDiseasesA.removeAll(uniqueDiseasesB);

    uniqueDiseasesB.addAll(diseasesB);
    uniqueDiseasesB.removeAll(uniqueDiseasesA);

    return "<html><font color=\"orange\">" + StringUtils.join(commonDiseases, ", ") + "</font> "
            + "<font color=\"green\">" + StringUtils.join(uniqueDiseasesA, ", ") + "</font> "
            + "<font color=\"blue\">" + StringUtils.join(uniqueDiseasesB, ", ") + "</font></html>";

}

From source file:FastArrayList.java

/**
 * Remove from this collection all of its elements except those that are
 * contained in the specified collection.
 *
 * @param collection Collection containing elements to be retained
 *
 * @exception UnsupportedOperationException if this optional operation
 *  is not supported by this list/* w  w  w .  j a  v  a2s .  com*/
 */
public boolean retainAll(Collection collection) {

    if (fast) {
        synchronized (this) {
            ArrayList temp = (ArrayList) list.clone();
            boolean result = temp.retainAll(collection);
            list = temp;
            return (result);
        }
    } else {
        synchronized (list) {
            return (list.retainAll(collection));
        }
    }

}

From source file:uk.ac.edukapp.service.WidgetProfileService.java

/**
 * //from w w  w  . j  a v  a2s .  com
 * @param categories
 * @return
 */
public SearchResults returnWidgetProfilesFilteredByCategories(List<List<Category>> categories) {
    ArrayList<Widgetprofile> widgetList = new ArrayList<Widgetprofile>();

    for (List<Category> group : categories) {
        HashSet<Widgetprofile> groupList = new HashSet<Widgetprofile>();
        for (Category category : group) {
            List<Widgetprofile> widgets = category.getWidgetprofiles();
            if (widgets != null) {
                groupList.addAll(widgets);
            }

        }
        if (widgetList.isEmpty()) {
            widgetList.addAll(groupList);
        } else {
            if (!groupList.isEmpty()) {
                widgetList.retainAll(groupList);
            }
        }
    }
    SearchResults sr = new SearchResults();
    sr.setWidgets(widgetList);
    sr.setNumber_of_results(widgetList.size());
    return sr;
}

From source file:trendanalisis.main.tools.weka.CoreWekaTFIDF.java

/**
 * Normalizes given instance to average doc length (only the newly constructed
 * attributes)./*from  www .j  a  v a 2  s . com*/
 * 
 * @param inst the instance to normalize
 * @param firstCopy
 * @throws Exception if avg. doc length not set
 */
private void normalizeInstance(Instance inst, int firstCopy, int indexInstance) throws Exception {

    String subtittle = "";
    ArrayList<String> subtittles = null;
    if (ins_fitur_subtitle != null) {
        subtittle = ins_fitur_subtitle.get(indexInstance).stringValue(0);
        subtittles = new ArrayList<>(Arrays.asList(subtittle.split(" ")));

        subtittles.retainAll(Words.values());

    } else {

        fitur_subtitle = false;
    }

    double docLength = 0;

    if (m_AvgDocLength < 0) {
        throw new Exception("Average document length not set.");
    }

    // Compute length of document vector
    for (int j = 0; j < inst.numValues(); j++) {
        if (inst.index(j) >= firstCopy) {

            if (m_filterType == FILTER_NORMALIZE_COSTUMIZE) {

                double score = ScoreTittle(subtittles, inst.index(j));
                inst.setValueSparse(j, inst.valueSparse(j) + score);

                docLength += inst.valueSparse(j);
            } else {
                docLength += inst.valueSparse(j) * inst.valueSparse(j);
            }

        }
    }

    NormalLengt[indexInstance] = docLength;

    if (m_filterType != FILTER_NORMALIZE_COSTUMIZE) {
        docLength = Math.sqrt(docLength);
    }

    // Normalize document vector
    for (int j = 0; j < inst.numValues(); j++) {
        if (inst.index(j) >= firstCopy) {

            double val = 0;
            // val = inst.valueSparse(j) / docLength;

            if (m_filterType == FILTER_NORMALIZE_COSTUMIZE) {

                val = (val + inst.valueSparse(j)) / docLength;

            } else {
                val = inst.valueSparse(j) * m_AvgDocLength / docLength;
            }

            // val*=10;// agar nilai tidak terlalu kecil
            inst.setValueSparse(j, val);

            if (val == 0) {
                System.err.println("setting value " + inst.index(j) + " to zero.");
                j--;
            }
        }
    }
}

From source file:net.i2cat.netconf.NetconfSession.java

public void connect() throws TransportException, NetconfProtocolException {
    RPCElement reply;//from   w  ww .j a v  a  2 s . co  m
    Hello clientHello;
    Hello serverHello;

    ArrayList<Capability> activeCapabilities;
    ArrayList<Capability> clientCapabilities;
    ArrayList<Capability> serverCapabilities;

    messageQueue = new MessageQueue();
    messageQueue.addListener(this);

    try {
        transport = transportFactory.getTransport(sessionContext.getURI().getScheme());
    } catch (TransportNotRegisteredException e) {
        TransportException te = new TransportException(e.getMessage());
        te.initCause(e);
        throw te;
    }

    transport.setMessageQueue(messageQueue);
    transport.addListener(this);

    // initialize message id
    sessionContext.setLastMessageId(0);

    transport.connect(sessionContext);
    log.info("Transport connected");

    clientHello = new Hello();
    clientCapabilities = Capability.getSupportedCapabilities();
    clientHello.setCapabilities(clientCapabilities);

    log.info("Sending hello");
    transport.sendAsyncQuery(clientHello);

    try {
        if (sessionContext.containsKey(SessionContext.TIMEOUT)) {
            reply = messageQueue.blockingConsumeById("0", sessionContext.getTimeout());
        } else {
            reply = messageQueue.blockingConsumeById("0");
        }
    } catch (UncheckedTimeoutException e) {
        throw new TransportException("No reply to hello -- timeout.", e);
    } catch (Exception e) {
        throw new TransportException("Error while getting reply: " + e.getMessage(), e);
    }

    // message-id, it is
    // indexed under 0.

    if (!(reply instanceof Hello))
        throw new NetconfProtocolException("First element received from server is not a <hello> message.");
    else
        serverHello = (Hello) reply;

    log.info("Received server hello.");
    this.sessionId = serverHello.getSessionId();

    // trim to common capabilities.
    serverCapabilities = serverHello.getCapabilities();
    activeCapabilities = (ArrayList<Capability>) clientCapabilities.clone();
    activeCapabilities.retainAll(serverCapabilities);

    log.debug("ACT_CAP " + activeCapabilities);

    sessionContext.setActiveCapabilities(activeCapabilities);
    sessionContext.setClientCapabilities(clientCapabilities);
    sessionContext.setServerCapabilities(serverCapabilities);

    log.info("Session " + this.sessionId + " opened with:");
    for (Capability capability : activeCapabilities)
        log.info(" - Capability: " + capability);

    /* Activate flags */

    // Activate keep Alive command
    // timerKeepAlive = new TimerKeepAlive(this);
    // timerKeepAlive.start(PERIOD);

}

From source file:it.polimi.geinterface.GroupEntityManager.java

/**
 * Method used to handle a {@link MessageType#SYNC_REQ} message: if the <code>group</code> is matched
 * and the computed {@link DistanceRange} is less or equal than <code>distanceRange</code>, a 
 * {@link MessageType#SYNC_RESP} message is sent on the topic <code>topic</code>
 * @param topic - the topic where the {@link MessageType#SYNC_RESP} has to be sent
 * @param beacons - beacons contained in the {@link MessageType#SYNC_REQ} message
 * @param group - the {@link Group} that has to be matched
 * @param distanceRange - the {@link DistanceRange} that has to be matched
 *//*from  w w w  . j a va2  s  .  c  om*/
private void handleSyncReq(final String topic, final ArrayList<Entity> beacons, final JSONObject group,
        final DistanceRange distanceRange) {

    scheduler.schedule(new Runnable() {

        @Override
        public void run() {

            PropertiesFilter filter = null;

            DistanceRange maxDistance = distanceRange;

            if (!((String) group.get(JsonStrings.FILTER)).equals(""))
                try {
                    filter = PropertiesFilter.parseFromString((String) group.get(JsonStrings.FILTER));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            String entityId = (String) group.get(JsonStrings.ENTITY_ID);
            Type entityType = Type.valueOf((String) group.get(JsonStrings.ENTITY_TYPE));
            String groupDesc = (String) group.get(JsonStrings.GROUP_DESCRIPTOR);

            Group g = new Group.Builder(groupDesc).setEntityID(entityId).setEntityType(entityType)
                    .setFilter(filter).build();

            if (!g.evaluate(selfEntity))
                return;

            DistanceRange bestDistance = DistanceRange.SAME_WIFI;
            ArrayList<Entity> queue;

            synchronized (lastSeenBeacons) {
                queue = new ArrayList<>(lastSeenBeacons);
                //intersection to obtain common beacons
                beacons.retainAll(lastSeenBeacons);
            }

            Builder builder = new Builder(selfEntity.getEntityID(), Type.DEVICE);
            JSONObject selfProps = selfEntity.getProperties();
            builder.addProperties(selfProps);

            if (beacons.size() == 0) {
                if (DistanceRange.SAME_WIFI.ordinal() <= maxDistance.ordinal()) {
                    builder.setDistance(DistanceRange.SAME_WIFI);
                    networkClient.publishMessage(topic,
                            MessageUtils.buildSyncRespMessage(builder.build(), topic));
                }
                return;
            }

            for (Entity common : beacons)
                for (Entity mine : queue)
                    if (common.equals(mine))
                        switch (common.getDistanceRange()) {
                        case IMMEDIATE:
                        case NEXT_TO:
                            bestDistance = (mine.getDistanceRange().ordinal() < bestDistance.ordinal())
                                    ? ((mine.getDistanceRange().ordinal() < common.getDistanceRange().ordinal())
                                            ? common.getDistanceRange()
                                            : mine.getDistanceRange())
                                    : bestDistance;
                            break;

                        default:
                            bestDistance = (mine.getDistanceRange().ordinal() <= DistanceRange.NEXT_TO.ordinal()
                                    && common.getDistanceRange().ordinal() < bestDistance.ordinal())
                                            ? common.getDistanceRange()
                                            : bestDistance;
                            break;
                        }

            if (bestDistance.ordinal() <= maxDistance.ordinal()) {
                builder.setDistance(bestDistance);
                networkClient.publishMessage(topic, MessageUtils.buildSyncRespMessage(builder.build(), topic));
            }
        }
    });

}