Klausos Klausos
Klausos Klausos

Reputation: 16050

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.

Upvotes: 1

Views: 73

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500425

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);
}

Upvotes: 3

arshajii
arshajii

Reputation: 129507

You might find it easier to create a new list instead of trying to modify the original list in place:

Set<Integer> used = new HashSet<>(usedElements);  // maybe use a set in the
                                                  // first place?

List<Integer> newElements = 
                       new ArrayList<>(elements.size() - used.size());

for (int i = 0; i < elements.size(); i++) {
    if (!used.contains(i))
        newElements.add(elements.get(i));
}

elements = newElements;

This entire process is O(n).

Upvotes: 2

Related Questions