Delete those elements from the list that are indexed in another list

List<Double> elements = new ArrayList<Double>();
List<Integer> usedElements = new ArrayList<Integer>();

for (int i=0; i<usedElements.size(); i++)
{
    elements.remove(usedElements.get(i));       
}

There is a List of indexes called usedElements. I need to delete those elements from the List elements that are mentioned in usedElements. How to do this in a correct way.

Jon Skeet
people
quotationmark

If you know your usedElements list is in ascending order, the simplest approach would be to remove the elements in reverse order - that way the "shuffling up" effect won't affect any of the later operations:

List<Double> elements = ...;
List<Integer> usedElements = ...;

for (int i = usedElements.size() - 1; i >= 0; i--) {
    elements.remove(usedElements.get(i));       
}

If usedElements isn't currently sorted, it would be best to just sort it first. If usedElements isn't currently sorted and you need to maintain its current order for another reason, then create a copy first, and sort that:

List<Double> elements = ...;
List<Integer> usedElements = ...;
List<Integer> sortedUsedElements = new ArrayList<Integer>(usedElements);
Collections.sort(sortedUsedElements);

for (int i = sortedUsedElements.size() - 1; i >= 0; i--) {
    elements.remove(sortedUsedElements.get(i));       
}

Or even sort the copy in reverse order and use an enhanced for loop:

List<Double> elements = ...;
List<Integer> usedElements = ...;
List<Integer> sortedUsedElements = new ArrayList<Integer>(usedElements);
Collections.sort(sortedUsedElements, Collections.<Integer>reverseOrder());

for (Integer index : sortedUsedElements) {
    elements.remove(index);
}

people

See more on this question at Stackoverflow