mutates list by removing set of indices from a list - Java java.lang

Java examples for java.lang:String Algorithm

Description

mutates list by removing set of indices from a list

Demo Code


//package com.java2s;

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;

public class Main {
    /**/*  w w  w. j a  v  a  2  s . c o m*/
     * mutates list by removing set of indices from a list
     * @param list List of objects that will be trimmed
     * @param toBeRemoved List<Integer> of indices to be removed
     */
    public static void removeIndices(Iterable<?> list,
            Collection<Integer> toBeRemoved) {

        //remove duplicates discarding order
        HashSet<Integer> h = new HashSet<Integer>(toBeRemoved);
        toBeRemoved.clear();
        toBeRemoved.addAll(h);

        //remove valid subtractions
        int i = 0;
        Iterator<?> iter = list.iterator();
        while (iter.hasNext()) {
            iter.next();
            if (toBeRemoved.contains(i++)) {
                iter.remove();
            }
        }
    }
}

Related Tutorials