Example usage for java.util List remove

List of usage examples for java.util List remove

Introduction

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

Prototype

E remove(int index);

Source Link

Document

Removes the element at the specified position in this list (optional operation).

Usage

From source file:acromusashi.stream.ml.clustering.kmeans.KmeansCalculator.java

/**
 * KMeans++?????/*  www .  jav a2 s .  c  o m*/
 * 
 * @param basePoints ??
 * @param clusterNum 
 * @return 
 */
public static List<KmeansPoint> createInitialCentroids(List<KmeansPoint> basePoints, int clusterNum) {
    Random random = new Random();
    List<KmeansPoint> resultList = Lists.newArrayList();
    // ??????????
    List<KmeansPoint> pointList = Lists.newArrayList(basePoints);
    KmeansPoint firstCentroid = pointList.remove(random.nextInt(pointList.size()));
    resultList.add(firstCentroid);

    double[] dxs;
    // KMeans++??????
    // ??1????????1????
    for (int centroidIndex = 1; centroidIndex < clusterNum; centroidIndex++) {
        // ?????????????
        dxs = computeDxs(pointList, resultList);

        // ??????????
        double r = random.nextDouble() * dxs[dxs.length - 1];
        int next = Arrays.binarySearch(dxs, r);
        int index = 0;
        if (next > 0) {
            index = next - 1;
        } else if (next < 0) {
            index = COMPENSATE_INDEX - next;
        }

        while (index > 0 && resultList.contains(pointList.get(index))) {
            index = index - 1;
        }

        resultList.add(pointList.get(index));
    }

    return resultList;
}

From source file:com.ace.console.service.sys.impl.ResourceServiceImpl.java

private static void recursiveMenu(Menu menu, List<Resources> resources) {
    for (int i = resources.size() - 1; i >= 0; i--) {
        Resources resource = resources.get(i);
        if (resource.getParentId() != null && resource.getParentId().equals(menu.getId())) {
            menu.getChildren().add(convertToMenu(resource));
            resources.remove(i);
        }//from   w ww .ja  va 2s  . com
    }

    for (Menu subMenu : menu.getChildren()) {
        recursiveMenu(subMenu, resources);
    }
}

From source file:it.unibo.alchemist.model.implementations.reactions.SAPEREReaction.java

/**
 * This method screens the lsaMolecule list, deleting all molecule which can
 * be covered from another one more generic.
 * /*w w w .  java  2s  .  co  m*/
 * @param listmol
 *            List of lsaMolecule to screen
 */
private static void screen(final List<Molecule> listmol) {
    /*
     * PHASE 1: generalize the list
     */
    for (int i = 0; i < listmol.size(); i++) {
        listmol.add(((ILsaMolecule) listmol.remove(0)).generalize());
    }
    /*
     * PHASE2: compare one-by-one
     */
    for (int i = listmol.size() - 1; i > 0; i--) {
        for (int p = i - 1; p >= 0; p--) {
            final ILsaMolecule m1 = (ILsaMolecule) listmol.get(i);
            final ILsaMolecule m2 = (ILsaMolecule) listmol.get(p);
            if (m2.equals(m1) || m2.moreGenericOf(m1)) {
                listmol.remove(i);
                i--;
            } else if (m1.moreGenericOf(m2)) {
                listmol.remove(p);
                i--;
            }
        }
    }
}

From source file:cascading.util.Util.java

/**
 * This method removes all nulls from the given List.
 *
 * @param list/*  w  ww.  j ava 2 s.c o m*/
 */
@SuppressWarnings({ "StatementWithEmptyBody" })
public static void removeAllNulls(List list) {
    while (list.remove(null))
        ;
}

From source file:gov.nih.nci.caIMAGE.util.NewDropdownUtil.java

/**
 * Add "" to the list in the first spot if it's not already there. Removes
 * it and put's it in the first spot if it is.
 *//*w w  w  .j a v a2  s. c  o  m*/
private static void addBlank(List inList) {

    if (!inList.contains("")) {
        inList.add(0, "");
    } else {
        inList.remove("");
        inList.add(0, "");
    }
}

From source file:Main.java

/**
 * Returns a three-element array of mutable {@code List}s:
 * <ol>//  w  w w  .j  ava  2 s .  co  m
 *    </li>
 *      the intersection of {@code a} and {@code b}
 *    <li>
 *    </li>
 *      the {@code a} - {@code b} difference
 *    <li>
 *    </li>
 *      the {@code b} - {@code a} difference
 *    <li>
 * </ol>
 *
 * @param       comparator
 *          a comparator to sort results, or {@code null} to remain
 *          unsorted
 */
public static <T> List<T>[] getIntersectAndDiffs(Collection<? extends T> a, Collection<? extends T> b,
        Comparator<T> comparator) {

    int aSize = a.size();
    List<T> aDiff = new ArrayList<T>(aSize);
    aDiff.addAll(a);

    int bSize = b.size();
    List<T> bDiff = new ArrayList<T>(bSize);
    bDiff.addAll(b);

    if (comparator != null) {
        Collections.sort(aDiff, comparator);
        Collections.sort(bDiff, comparator);
    }

    List<T> abInter = new ArrayList<T>(Math.min(aSize, bSize));

    for (int i = aDiff.size() - 1; i >= 0; i--) {
        T element = aDiff.get(i);

        int index = comparator == null ? bDiff.indexOf(element)
                : Collections.binarySearch(bDiff, element, comparator);

        if (index != -1) {
            bDiff.remove(index);
            aDiff.remove(i);
            abInter.add(element);
        }
    }

    @SuppressWarnings({ "unchecked" })
    List<T>[] array = (List<T>[]) new List[] { abInter, aDiff, bDiff };

    return array;
}

From source file:edu.berkeley.sparrow.examples.BackendBenchmarkProfiler.java

/**
 * Run an experiment which launches tasks at {@code arrivalRate} for {@code durationMs}
 * seconds and waits for all tasks to finish. Return a {@link DescriptiveStatistics}
 * object which contains stats about the distribution of task finish times. Tasks
 * are executed in a thread pool which contains at least {@code corePoolSize} threads
 * and grows up to {@code maxPoolSize} threads (growing whenever a new task arrives
 * and all existing threads are used). /*from   ww  w  .j  a va  2  s.c o m*/
 * 
 * Setting {@code maxPoolSize} to a very large number enacts time sharing, while
 * setting it equal to {@code corePoolSize} creates a fixed size task pool.
 * 
 * The derivative of task finishes is tracked by bucketing tasks at the granularity
 * {@code bucketSize}. If it is detected that task finishes are increasing in an 
 * unbounded fashion (i.e. infinite queuing is occuring) a {@link RuntimeException} 
 * is thrown.
 */
public static void runExperiment(double arrivalRate, int corePoolSize, int maxPoolSize, long bucketSize,
        long durationMs, DescriptiveStatistics runTimes, DescriptiveStatistics waitTimes) {
    long startTime = System.currentTimeMillis();
    long keepAliveTime = 10;
    Random r = new Random();
    BlockingQueue<Runnable> runQueue = new LinkedBlockingQueue<Runnable>();
    ExecutorService threadPool = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime,
            TimeUnit.MILLISECONDS, runQueue);
    if (maxPoolSize == Integer.MAX_VALUE) {
        threadPool = Executors.newCachedThreadPool();
    }

    // run times indexed by bucketing interval
    HashMap<Long, List<Long>> bucketedRunTimes = new HashMap<Long, List<Long>>();
    // wait times indexed by bucketing interval
    HashMap<Long, List<Long>> bucketedWaitTimes = new HashMap<Long, List<Long>>();

    /*
     * This is a little tricky. 
     * 
     * We want to generate inter-arrival delays according to the arrival rate specified.
     * The simplest option would be to generate an arrival delay and then sleep() for it
     * before launching each task. This has in issue, however: sleep() might wait 
     * several ms longer than we ask it to. When task arrival rates get really fast, 
     * i.e. one task every 10 ms, sleeping an additional few ms will mean we launch 
     * tasks at a much lower rate than requested.
     * 
     * Instead, we keep track of task launches in a way that does not depend on how long
     * sleep() actually takes. We still might have tasks launch slightly after their
     * scheduled launch time, but we will not systematically "fall behind" due to
     * compounding time lost during sleep()'s;
     */
    long currTime = startTime;
    while (true) {
        long delay = (long) (generateInterarrivalDelay(r, arrivalRate) * 1000);

        // When should the next task launch, based on when the last task was scheduled
        // to launch.
        long nextTime = currTime + delay;

        // Diff gives how long we should wait for the next scheduled task. The difference 
        // may be negative if our last sleep() lasted too long relative to the inter-arrival
        // delay based on the last scheduled launch, so we round up to 0 in that case. 
        long diff = Math.max(0, nextTime - System.currentTimeMillis());
        currTime = nextTime;
        if (diff > 0) {
            try {
                Thread.sleep(diff);
            } catch (InterruptedException e) {
                System.err.println("Unexpected interruption!");
                System.exit(1);
            }
        }
        threadPool.submit((new BenchmarkRunnable(bucketedRunTimes, bucketedWaitTimes, bucketSize)));
        if (System.currentTimeMillis() > startTime + durationMs) {
            break;
        }
    }
    threadPool.shutdown();
    try {
        threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e1) {
        System.err.println("Unexpected interruption!");
        System.exit(1);
    }
    List<Long> times = new ArrayList<Long>(bucketedRunTimes.keySet());
    Collections.sort(times);
    HashMap<Long, DescriptiveStatistics> bucketStats = new HashMap<Long, DescriptiveStatistics>();

    // Remove first and last buckets since they will not be completely full to do
    // discretization. 
    times.remove(0);
    times.remove(times.size() - 1);

    for (Long time : times) {
        DescriptiveStatistics stats = new DescriptiveStatistics();
        List<Long> list = bucketedRunTimes.get(time);
        for (Long l : list) {
            stats.addValue(l);
            runTimes.addValue(l);
        }
        bucketStats.put(time, stats);

        List<Long> waitList = bucketedWaitTimes.get(time);
        for (Long l : waitList) {
            waitTimes.addValue(l);
        }
    }
    int size = bucketStats.size();
    if (size >= 2) {
        DescriptiveStatistics first = bucketStats.get(times.get(0));
        DescriptiveStatistics last = bucketStats.get(times.get(times.size() - 1));
        double increase = last.getPercentile(50) / first.getPercentile(50);
        // A simple heuristic, if the median runtime went up by five from the first to 
        // last complete bucket, we assume we are seeing unbounded growth
        if (increase > 5.0) {
            throw new RuntimeException(
                    "Queue not in steady state: " + last.getMean() + " vs " + first.getMean());
        }
    }
}

From source file:Main.java

private static void iterativeData(List<Map<String, Object>> datas, List<Map<String, Object>> parentDatas,
        String idField, String parentIdFiled) {
    int length = parentDatas.size();
    Map data = null;//from   w  w w .  ja  v  a 2  s . co  m

    for (int i = 0; i < length; ++i) {
        data = (Map) parentDatas.get(i);
        ArrayList children = new ArrayList();
        data.put("children", children);
        int len = datas.size();
        Map d = null;

        for (int j = 0; j < len; ++j) {
            d = (Map) datas.get(j);
            if (data.get(idField).equals(d.get(parentIdFiled))) {
                children.add(d);
                datas.remove(j);
                --j;
                --len;
            }
        }

        iterativeData(datas, children, idField, parentIdFiled);
    }

}

From source file:com.aurel.track.admin.customize.category.filter.parameters.FilterSelectsParametersUtil.java

/**
 * Prepares the filterUpperTO for setting the parameters
 * 1. by first rendering the parameterized fields of filterSelectsTO
 * 2. after project change in the already rendered parameterized fields of filterSelectsTO
 * to refresh the other, project dependent parameterized fields
 * @param originalFilterUpperTO/*  w  w w .j  av  a  2 s. c  o m*/
 * @param parameterFilterUpperTO
 * @param personBean
 * @param locale
 * @return
 */
public static Integer[] prepareParameterFilterSelects(FilterUpperTO originalFilterUpperTO,
        FilterUpperTO parameterFilterUpperTO, TPersonBean personBean, Locale locale) {
    Integer[] originalSelectedProjects = originalFilterUpperTO.getSelectedProjects();
    List<Integer> parameterizedUpperFields = new LinkedList<Integer>();
    parameterFilterUpperTO.setUpperFields(parameterizedUpperFields);
    /*
     * get the selected projects
     */
    //the data in some other lists depends on the current project selection 
    Integer[] selectedProjects;
    if (containsParameter(originalSelectedProjects)) {
        //remove the projects which are selected in the originalReportConfigBean  
        //allProjects = removeSelected(originalSelectedProjects, allProjects);
        //render the projects list only if contains parameter
        //parameterFilterUpperTO.setProjects(allProjects);
        //gather the two project selections together
        Integer[] originalSelection = originalFilterUpperTO.getSelectedProjects();
        selectedProjects = getSelectedWithoutParam(originalSelection);
        parameterizedUpperFields.add(SystemFields.INTEGER_PROJECT);
        parameterFilterUpperTO.setProjectTree(ProjectPickerBL.getTreeNodesForRead(
                GeneralUtils.createSetFromIntegerArr(selectedProjects), true, false, personBean, locale));
    } else {
        //do not render the project list
        selectedProjects = originalFilterUpperTO.getSelectedProjects();
    }
    Integer[] ancestorProjects = null;
    if (selectedProjects == null || selectedProjects.length == 0) {
        //none of the projects is selected -> get the other lists datasource as all available projects would be selected
        List<TProjectBean> projectBeans = ProjectBL.loadUsedProjectsFlat(personBean.getObjectID());
        if (projectBeans != null && !projectBeans.isEmpty()) {
            selectedProjects = GeneralUtils
                    .createIntegerArrFromCollection(GeneralUtils.createIntegerListFromBeanList(projectBeans));
            ancestorProjects = selectedProjects;
        }
    } else {
        ancestorProjects = ProjectBL.getAncestorProjects(selectedProjects);
    }
    List<Integer> upperSelectFields = getUpperSelectFields(originalFilterUpperTO);
    //project is already prepared explicitly 
    upperSelectFields.remove(SystemFields.INTEGER_PROJECT);
    /*
     * get the watchers (no fieldType based datasource)
     */
    Integer[] selectedConsultantsInformants = originalFilterUpperTO.getSelectedConsultantsInformants();
    if (containsParameter(selectedConsultantsInformants)) {
        Integer[] selectedWithoutParam = getSelectedWithoutParam(selectedConsultantsInformants);
        parameterFilterUpperTO.setSelectedConsultantsInformants(selectedWithoutParam);
        parameterFilterUpperTO.setConsultantsInformants(FilterSelectsListsLoader.getConsultantsInformants(
                selectedProjects, ancestorProjects, personBean.getObjectID(), false, null, locale));
        parameterizedUpperFields.add(Integer.valueOf(PSEUDO_FIELDS.CONSULTANT_INFORMNAT_FIELD_ID));
    }
    upperSelectFields.remove(Integer.valueOf(PSEUDO_FIELDS.CONSULTANT_INFORMNAT_FIELD_ID));
    /*
     * get all other selects 
     */
    for (Integer fieldID : upperSelectFields) {
        Integer[] selectedValues = originalFilterUpperTO.getSelectedValuesForField(fieldID);
        if (containsParameter(selectedValues)) {
            IFieldTypeRT fieldTypeRT = FieldTypeManager.getFieldTypeRT(fieldID);
            Integer[] selectedWithoutParam = getSelectedWithoutParam(selectedValues);
            parameterFilterUpperTO.setSelectedValuesForField(fieldID, selectedWithoutParam);
            MatcherDatasourceContext matcherDatasourceContext = new MatcherDatasourceContext(selectedProjects,
                    ancestorProjects, originalFilterUpperTO.getSelectedIssueTypes(), personBean, locale, false,
                    true, originalFilterUpperTO.isShowClosedReleases(), false);
            Object datasource = fieldTypeRT.getMatcherDataSource(
                    new MatcherExpressionBase(fieldID, selectedWithoutParam), matcherDatasourceContext, null);
            if (FieldBL.isTree(fieldID)) {
                parameterFilterUpperTO.setTreeDatasourceForField(fieldID, (List<TreeNode>) datasource);
            } else {
                parameterFilterUpperTO.setListDatasourceForField(fieldID, (List<ILabelBean>) datasource);
            }
            parameterizedUpperFields.add(fieldID);
        }
    }
    return selectedProjects;
}

From source file:MultiMap.java

public static Object remove(Object list, Object o) {
    if (list == null)
        return null;

    if (list instanceof List) {
        List l = (List) list;
        l.remove(o);
        if (l.size() == 0)
            return null;
        return list;
    }//from ww w .jav  a  2  s  .  c  om

    if (list.equals(o))
        return null;
    return list;
}