Example usage for java.util ArrayList removeAll

List of usage examples for java.util ArrayList removeAll

Introduction

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

Prototype

public boolean removeAll(Collection<?> c) 

Source Link

Document

Removes from this list all of its elements that are contained in the specified collection.

Usage

From source file:nz.co.fortytwo.freeboard.server.GPXProcessor.java

public HashMap<String, Object> handle(HashMap<String, Object> map) {
    // <trkpt lat="-41.19408333" lon="173.24741667"><ele>2376</ele><time>2007-10-14T10:09:57Z</time></trkpt>
    if (map.containsKey(Constants.LAT) && map.containsKey(Constants.LON)) {
        // check if they are worth saving
        double newLat = (Double) map.get(Constants.LAT);
        double newLon = (Double) map.get(Constants.LON);
        // write out to gpx track
        TrackPoint tp = new TrackPoint();
        tp.setElevation(0.0);/*from   w ww  . j  av  a  2 s  .  com*/
        tp.setTime(new Date());
        tp.setLatitude(newLat);
        tp.setLongitude(newLon);
        currentTrack.getTrackPoints().add(tp);

        // we count every occurrence, an easy way to count time!
        count++;
    }
    // write out every 60 points, eg 1 min at 1 sec GPS data, or 60sec to usb
    if (count > triggerCount) {
        count = 0;
        // simplify here
        currentTrack.setTrackPoints(SGImplify.simplifyLine2D(TOLERANCE, currentTrack.getTrackPoints()));
        // if its still too long, truncate and archive
        if (currentTrack.getTrackPoints().size() > 1100) {
            // write out the first 1000
            ArrayList<Waypoint> points = currentTrack.getTrackPoints();

            Waypoint[] oldPoints = Arrays.copyOfRange(points.toArray(new Waypoint[0]), 0, 1000);
            GPX oldGpx = new GPX();
            Track oldTrack = new Track();
            ArrayList<Waypoint> newPoints = new ArrayList<Waypoint>();
            newPoints.addAll(Arrays.asList(oldPoints));

            oldTrack.setTrackPoints(newPoints);
            oldGpx.addTrack(oldTrack);

            String fileName = Util.sdf.format(new Date());
            oldTrack.setName(CURRENT + " " + fileName);
            writeGPX(oldGpx, new File(gpxDir, fileName + ".gpx"));

            points.removeAll(newPoints);
            currentTrack.setTrackPoints(points);
        }

        writeGPX(gpx, gpxFile);

    }
    return map;
}

From source file:org.strasa.middleware.manager.CreateFieldBookManagerImpl.java

/**
 * Validate germplasm./*  w  ww . j a v  a2s. c  om*/
 * 
 * @param sheet
 *            the sheet
 * @throws Exception
 *             the exception
 */
public void validateGermplasm(Sheet sheet) throws Exception {

    Integer colNum = getHeaderColumnNumber("Gname", sheet);

    ArrayList<String> lstGermplasm = readRowsByColumn(sheet, 1, colNum).get(0);

    HashSet<String> uniqueGerm = new HashSet<String>();
    uniqueGerm.addAll(lstGermplasm);
    ArrayList<String> lstUnknownGerm = new ArrayList<String>();
    lstUnknownGerm.addAll(uniqueGerm);
    lstUnknownGerm
            .removeAll(new GermplasmManagerImpl().getGermplasmBatchAsString(new ArrayList<String>(uniqueGerm)));

    // System.out.println("GEMR: " + lstGermplasm.get(0));
    if (!lstUnknownGerm.isEmpty()) {
        System.out.println("Error: Unknown Germplasm detected {"
                + StringUtils.join(lstUnknownGerm.toArray(new String[lstUnknownGerm.size()]), ", "));

        throw new CreateFieldBookException("Error: Unknown Germplasm detected {"
                + StringUtils.join(lstUnknownGerm.toArray(new String[lstUnknownGerm.size()]), ", ") + "}");
    }
}

From source file:Test.ScenarioBail.java

public ScenarioBail(density_tasks DensTask, spatial_concentration SpatConc, degree_of_modularity Mod,
        score_dispersion DispScore, sensors_dispersion DispSens, boolean random, int scenarioWidth) {
    //assignment/*  w w w  .  j a v  a 2  s.c o  m*/
    this.DensTask = DensTask;
    this.DispScore = DispScore;
    this.DispSens = DispSens;
    this.Mod = Mod;
    this.SpatConc = SpatConc;

    switch (DensTask) {
    case high:
        this.number_of_bails = 30;
        break;
    case low:
        this.number_of_bails = 6;
        break;
    }
    if (SpatConc == spatial_concentration.high) {
        if (random == false) {
            if (number_of_bails == 30) {
                Collections.addAll(this.positions, this.position_30bails_50width1rnd);
            } else {
                Collections.addAll(this.positions, this.position_6bails_50width1rnd);
            }
        } else {

            int v1 = (int) (Math.random() * (scenarioWidth - 16));
            int v2 = (int) (Math.random() * (scenarioWidth - 16));
            v2 = v2 * scenarioWidth;
            ArrayList<Integer> concentrPoints = new ArrayList();
            for (int i = 0; i < 15; i++) {
                int k = v2 + scenarioWidth * i;
                for (int j = k + v1; j < k + v1 + 15; j++) {
                    concentrPoints.add(j);
                }
            }
            ArrayList<Integer> allPoints = new ArrayList();
            ArrayList<Integer> diffPoints = new ArrayList();
            for (int i = 0; i < scenarioWidth * scenarioWidth; i++) {
                allPoints.add(i);
            }
            diffPoints.addAll(allPoints);
            diffPoints.removeAll(concentrPoints);
            EnumeratedIntegerDistribution randomizer;
            Double probDiff = (double) 0 / diffPoints.size();
            Double probConc = (double) 1 / concentrPoints.size();
            double[] probVector = new double[allPoints.size()];
            for (int i = 0; i < allPoints.size(); i++) {
                if (diffPoints.contains(i)) {
                    probVector[i] = probDiff;
                } else {
                    probVector[i] = probConc;
                }
            }
            int[] allPointsarray = allPoints.stream().mapToInt(i -> i).toArray();
            EnumeratedIntegerDistribution randomizerPosition;
            randomizerPosition = new EnumeratedIntegerDistribution(allPointsarray, probVector);
            for (int u = 0; u < this.number_of_bails; u++) {
                this.positions.add(randomizerPosition.sample());

            }
        }
    } else {
        if (random == false) {
            if (number_of_bails == 30) {
                Collections.addAll(this.positions, this.position_30bails_50width1rnd);
            } else {
                Collections.addAll(this.positions, this.position_6bails_50width1rnd);
            }
        } else {
            for (int u = 0; u < this.number_of_bails; u++) {
                int v1 = (int) (Math.random() * (scenarioWidth * scenarioWidth - 1));
                this.positions.add(v1);
            }
        }
    }
    Double high;
    Double low;
    high = 1200.0;
    low = 300.0;
    /*if (Mod == degree_of_modularity.two || Mod == degree_of_modularity.oneComptwo){
        high = 800.0;
        low = 200.0;
    } else {
        high = 1200.0;
        low = 300.0;      
    }*/
    if (DispScore == score_dispersion.high) {

        if (random == false) {

            if (this.number_of_bails == 30) {
                for (int u = 0; u < 6; u++) {
                    this.scores_30bails_50width1rnd[u] = this.scores_30bails_50width1rnd[u] + high;
                }
                Collections.addAll(this.scores, scores_30bails_50width1rnd);
            } else {
                Collections.addAll(this.scores, this.scores_6bails_50widthHDev);
            }
        } else {
            int numHigh = (int) ((int) this.number_of_bails * 0.2);
            int v = (int) (Math.random() * (this.number_of_bails - numHigh));
            ArrayList<Integer> bailsHigh = new ArrayList<>();
            Double sum = 0.0;
            for (int y = 0; y < this.number_of_bails; y++) {
                this.scores.add(Math.random() * low);

            }
            for (int i = v; i < v + numHigh; i++) {
                this.scores.add(i, Math.random() * low + high);

            }

        }
        adjustMean(this.scores, 30000.0);
    } else {
        if (random == false) {
            if (this.number_of_bails == 30) {
                Collections.addAll(this.scores, scores_30bails_50width1rnd);
            } else {
                Collections.addAll(this.scores, this.scores_6bails_50width);
            }
        } else {
            for (int j = 0; j < this.number_of_bails; j++) {
                this.scores.add(Math.random() * (high - low) + high / 2);
            }

        }
        adjustMean(this.scores, 30000.0);
    }
    ArrayList<String> sensors = new ArrayList();
    sensors.add("IR");

    switch (Mod) {
    case three:
        sensors.add("MW");
        sensors.add("AB");
        break;
    case two:
        sensors.add("MW");
        break;
    default:
        break;
    }

    int count = 0;
    if (DispSens == sensors_dispersion.high) {
        for (int j = 1; j <= sensors.size(); j++) {
            List<Set<String>> subset = getSubsets(sensors, j);
            EnumeratedIntegerDistribution randR;
            double[] probVec = new double[subset.size()];
            int[] mapSubset = new int[subset.size()];
            for (int t = 0; t < subset.size(); t++) {
                probVec[t] = (double) 1 / subset.size();
                mapSubset[t] = t;
            }
            randR = new EnumeratedIntegerDistribution(mapSubset, probVec);
            for (int y = 0; y < (int) this.number_of_bails / sensors.size(); y++) {
                Set<String> thisset = subset.get(randR.sample());
                ArrayList<String> thisarray = new ArrayList();
                thisarray.addAll(thisset);
                this.bail_sensor.put(count, thisarray);
                count++;
            }
        }
    } else {
        for (int j = 0; j < this.number_of_bails; j++) {
            this.bail_sensor.put(count, sensors);
            count++;
        }
    }
}

From source file:com.smash.revolance.ui.model.page.api.PageBean.java

public Map<DiffType, List<ElementBean>> getDiff(List<ElementBean> elements) throws Exception {
    Map<DiffType, List<ElementBean>> differencies = new HashMap<DiffType, List<ElementBean>>();

    ArrayList<ElementBean> baseElements = getBaseElements(elements);
    ArrayList<ElementBean> removedElements = getRemovedElements(elements);
    ArrayList<ElementBean> addedElements = getAddedElements(elements);

    ArrayList<ElementBean> updatedElements = updatedElements(addedElements, removedElements);

    baseElements.addAll(updatedElements);
    addedElements.removeAll(updatedElements);
    removedElements.removeAll(updatedElements);

    filterElementsIncludedInEachOthers(baseElements);
    Collections.sort(baseElements);
    differencies.put(DiffType.CHANGED, baseElements);

    filterElementsIncludedInEachOthers(removedElements);
    Collections.sort(removedElements);
    differencies.put(DiffType.DELETED, removedElements);

    filterElementsIncludedInEachOthers(addedElements);
    Collections.sort(addedElements);
    differencies.put(DiffType.ADDED, addedElements);

    return differencies;
}

From source file:org.eclipse.emf.teneo.ERuntime.java

/**
 * Retains only the root parent class in a list, so if an entry in the list as a parent in the
 * same list then the child is deleted from the list
 *///w w  w .  java2 s .  c o  m
private void cleanList(ArrayList<Class<?>> list) {
    final ArrayList<Class<?>> toRemove = new ArrayList<Class<?>>();
    for (Class<?> clazz : list) {
        if (clazz == null) {
            continue;
        }
        final Class<?>[] supers = clazz.getInterfaces();
        for (Class<?> element : supers) {
            if (list.contains(element)) {
                toRemove.add(clazz);
                break;
            }
        }
    }
    list.removeAll(toRemove);
}

From source file:com.nextgis.maplibui.mapui.NGWVectorLayerUI.java

@Override
public boolean delete() {
    File form = new File(mPath, ConstantsUI.FILE_FORM);
    if (form.exists()) {
        try {/*from w  w  w  .j  a va 2s  . co m*/
            ArrayList<String> lookupTableIds = LayerUtil.fillLookupTableIds(form);
            MapContentProviderHelper map = (MapContentProviderHelper) MapBase.getInstance();
            if (null == map)
                throw new IllegalArgumentException(
                        "The map should extends MapContentProviderHelper or inherited");

            for (int i = 0; i < map.getLayerCount(); i++) {
                if (map.getLayer(i) instanceof NGWVectorLayer) {
                    form = new File(map.getLayer(i).getPath(), ConstantsUI.FILE_FORM);
                    if (form.exists()) {
                        ArrayList<String> otherIds = LayerUtil.fillLookupTableIds(form);
                        lookupTableIds.removeAll(otherIds);
                    }
                }
            }

            if (lookupTableIds.size() > 0)
                for (int i = 0; i < map.getLayerCount(); i++) {
                    if (map.getLayer(i) instanceof NGWLookupTable) {
                        NGWLookupTable table = (NGWLookupTable) map.getLayer(i);
                        String id = table.getRemoteId() + "";
                        if (table.getAccountName().equals(mAccountName) && lookupTableIds.contains(id)) {
                            map.removeLayer(table);
                            table.delete();
                            i--;
                        }
                    }
                }
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
    }

    return super.delete();
}

From source file:org.strasa.middleware.manager.CreateFieldBookManagerImpl.java

/**
 * Validate site.//from  w ww  . j  ava2s  .c om
 * 
 * @param shObservation
 *            the sh observation
 * @param shSiteInfo
 *            the sh site info
 * @throws Exception
 *             the exception
 */
public void validateSite(Sheet shObservation, Sheet shSiteInfo) throws Exception {

    Integer colSite = getHeaderColumnNumber("Site", shObservation);
    HashSet<String> uniqueSite = new HashSet<String>();
    uniqueSite.addAll(readRowsByColumn(shObservation, 1, colSite).get(0));
    System.out.println(readRowsByColumn(shObservation, 1, colSite).get(0).get(0));
    ArrayList<String> lstUnknownSite = readRowsByColumn(shSiteInfo, 1, 0).get(0);
    if (lstUnknownSite.size() > uniqueSite.size()) {

        lstUnknownSite.removeAll(uniqueSite);
        throw new CreateFieldBookException("Invalid list of sites detected. Could not find {"
                + StringUtils.join(lstUnknownSite.toArray(new String[lstUnknownSite.size()]), ",")
                + "} in Observation sheet.");
    }
    if (uniqueSite.size() > lstUnknownSite.size()) {
        uniqueSite.removeAll(lstUnknownSite);
        throw new CreateFieldBookException("Invalid list of sites detected. Could not find {"
                + StringUtils.join(uniqueSite.toArray(new String[uniqueSite.size()]), ",")
                + "} in Site Information sheet.");

    }
    lstUnknownSite.removeAll(uniqueSite);
    if (!lstUnknownSite.isEmpty()) {
        throw new CreateFieldBookException("Invalid list of sites detected. Could not find {"
                + StringUtils.join(lstUnknownSite.toArray(new String[lstUnknownSite.size()]), ",")
                + "} in Site Information sheet.");

    }

}

From source file:org.collectionspace.services.common.vocabulary.nuxeo.AuthorityDocumentModelHandler.java

protected int syncAllItems(ServiceContext ctx, Specifier sasAuthoritySpecifier) throws Exception {
    int result = -1;
    int created = 0;
    int synched = 0;
    int alreadySynched = 0;
    int deprecated = 0;
    int totalItemsProcessed = 0;
    ArrayList<String> itemsInRemoteAuthority = new ArrayList<String>();
    ////from w w w.ja v  a 2 s.  c  o m
    // Iterate over the list of items/terms in the remote authority
    //
    PoxPayloadIn sasPayloadInItemList = requestPayloadInItemList(ctx, sasAuthoritySpecifier);
    List<Element> itemList = getItemList(sasPayloadInItemList);
    if (itemList != null) {
        for (Element e : itemList) {
            String remoteRefName = XmlTools.getElementValue(e, AuthorityItemJAXBSchema.REF_NAME);
            itemsInRemoteAuthority.add(XmlTools.getElementValue(e, AuthorityItemJAXBSchema.SHORT_IDENTIFIER));
            long status = syncRemoteItemWithLocalItem(ctx, remoteRefName);
            if (status == 1) {
                created++;
            } else if (status == 0) {
                synched++;
            } else {
                alreadySynched++;
            }
            totalItemsProcessed++;
        }
    }
    //
    // Now see if we need to deprecate or delete items that have been hard-deleted from the SAS but still exist
    // locally.  Subtract (remove) the list of remote items from the list of local items to determine which
    // of the remote items have been hard deleted.
    //
    ArrayList<String> itemsInLocalAuthority = getItemsInLocalAuthority(ctx, sasAuthoritySpecifier);
    itemsInLocalAuthority.removeAll(itemsInRemoteAuthority);
    if (itemsInLocalAuthority.size() > 0) {
        ArrayList<String> remainingItems = itemsInLocalAuthority; // now a subset of local items that no longer exist on the SAS, so we need to try to delete them (or mark them as deprecated if they still have records referencing them)
        //
        // We now need to either hard-delete or deprecate the remaining authorities
        //
        long processed = deleteOrDeprecateItems(ctx, sasAuthoritySpecifier, remainingItems);
        if (processed != remainingItems.size()) {
            throw new Exception(
                    "Encountered unexpected exception trying to delete or deprecated authority items during synchronization.");
        }
    }
    //
    // Now that we've sync'd all the items, we need to synchronize the hierarchy relationships
    //
    for (String itemShortId : itemsInRemoteAuthority) {
        long status = syncRemoteItemRelationshipsWithLocalItem(ctx, sasAuthoritySpecifier, itemShortId);
        if (status == 1) {
            created++;
        } else if (status == 0) {
            synched++;
        } else {
            alreadySynched++;
        }
        totalItemsProcessed++;
    }

    logger.info(String.format("Total number of items processed during sync: %d", totalItemsProcessed));
    logger.info(String.format("Number of items synchronized: %d", synched));
    logger.info(String.format("Number of items created during sync: %d", created));
    logger.info(String.format("Number not needing synchronization: %d", alreadySynched));

    return result;
}

From source file:com.chess.genesis.net.SyncClient.java

private ArrayList<String> getNeedList(final JSONArray ids) {
    try {/*from   w w  w  . ja  v  a2s  .c  o m*/
        final ArrayList<String> list_need = new ArrayList<String>(ids.length());
        for (int i = 0, len = ids.length(); i < len; i++)
            list_need.add(ids.getString(i));

        if (syncType == ACTIVE_SYNC || syncType == ARCHIVE_SYNC)
            return list_need;

        final GameDataDB db = new GameDataDB(context);
        final List<String> list = gameType == Enums.ONLINE_GAME ? db.getOnlineGameIds()
                : db.getArchiveGameIds();
        db.close();

        final ArrayList<String> list_have = new ArrayList<String>(list.size());
        for (final String item : list)
            list_have.add(item);

        list_need.removeAll(list_have);
        return list_need;
    } catch (final JSONException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:utybo.branchingstorytree.swing.editor.StoryNodesEditor.java

public void checkAllAvailable() {
    ArrayList<StorySingleNodeEditor> seen = new ArrayList<>();
    // Because the algorithm used can mark errors twice we use a set to ensure
    // it only contains each errored element once
    LinkedHashSet<StorySingleNodeEditor> toMarkAsError = new LinkedHashSet<>();
    for (StorySingleNodeEditor ssne : list) {
        for (StorySingleNodeEditor other : seen)
            if (other.matchesId(ssne)) {
                toMarkAsError.add(ssne);
                toMarkAsError.add(other);
                break;
            }//from www  .j  a  v  a 2s  . co m
        seen.add(ssne);
    }
    // Turn "seen" into the "everything is ok" list by removing all the errors
    seen.removeAll(toMarkAsError);
    seen.forEach(ssne -> {
        ssne.setStatus(Status.OK);
        ssne.getId().notifyOk();
    });
    toMarkAsError.forEach(ssne -> {
        ssne.setStatus(Status.ERROR);
        ssne.getId().notifyError();
    });
    jlist.repaint();
}