HungryForKnowledge
HungryForKnowledge

Reputation: 289

Arraylist in Java removing elements

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?

Upvotes: 0

Views: 3990

Answers (4)

jlordo
jlordo

Reputation: 37843

Sort list2 and delete items from list1 starting at the highest index given in list2. That way your other relevant indexes in list1 wont change.

You could do it like this:

    Collections.sort(list2, Collections.reverseOrder());
    for (Integer i : list2) {
        list1.remove((int) i);
    }

EDIT:

As pointed out by David Wallace in his comment, above approach only works if there are no duplicates in list2. You can get rid of duplicates by adding the following line before the code posted above:

list2 = new ArrayList<>(new HashSet<>(list2));

Upvotes: 4

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79875

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 in list1 to null. Then remove all the nulls from list1 at the end. This will work even if there are duplicate elements in list2, which jlordo's solution would have difficulty with.

for(Integer index : list2){
    list1.set(index,null);
}
list1.removeAll(Collections.singleton(null));

Upvotes: 3

AngerClown
AngerClown

Reputation: 6229

If you just care about insertion order, something like a LinkedHashMap work better for this. But, in order to determine an index, you would have to iterate over the list until you found the element you wanted:

int n = 0;
for (String value : linkedMap) {
  if (value.equals(valueToSearch)) {
    break;
   }
   ++n;
}
// n == index now

If you frequently need the indexes, then you probably just want 2 Maps. One that holds indexe -> String and the other holds String -> index. Just make sure you insert and remove from both maps at the same time.

Upvotes: 0

NAP-Developer
NAP-Developer

Reputation: 3796

Used for BaseAdapter and getView() method inside code write down and particular onClickListner imlement and try this out this code,

mArrayList.remove(position);
notifyDataSetChanged();

Upvotes: -3

Related Questions