I have 2 ArrayList, one containing Strings, the other Integers. The list2 contains indices of elements of list1.
Now I need to remove all the elements from list1 whose index is in list2. Any ideas?
ArrayList<String> list1 = new ArrayList<String>();
list1.add("a");
list1.add("b");
list1.add("c");
list1.add("d");
list1.add("e");
list1.add("f");
ArrayList<Integer> list2 = new ArrayList<Integer>();
list2.add(1);
list2.add(4);
list2.add(2);
The problem here is, you cannot remove from original list1 as the index will keep changing. I tried creating a temp HashMap to store the array index and String relation.
I iterate over list2 and map. When I found a matching key=index, I skipped that. Else I put String element in new list.
Any better suggestions?
This solution assumes that null is not a valid value in
list1.You could iterate through
list2, and for each index you get to, set the corresponding value inlist1to null. Then remove all the nulls fromlist1at the end. This will work even if there are duplicate elements inlist2, which jlordo’s solution would have difficulty with.