Search code examples
javaarraylistcollectionsremoveall

how can we remove multiple values in arrayList?


remove method we used for single remove, but I want to delete multiple values in array List.

ArrayList<Integer> al=new ArrayList<Integer>();
    al.add(7);
    al.add(8);
    al.add(9);
    al.add(13);
    al.add(22);
    al.add(55);
    al.add(88);
    //adding values
    for(int i=0;i<100;i++){
        al.add(i);
    }

I added duplicate elements, I want to fetch the duplicate elements and remove it from arraylist

for example:

output like:1, 2, 3, 4, 5, 6, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100


Solution

  • Use two ArrayLists, one with objects to remove and use removeAll method:

    Removes from this list all of its elements that are contained in the specified collection.

    ArrayList<Integer> toRemove=new ArrayList<>();//use diamond operator to reduce verbosity 
    toRemove.add(7);
    toRemove.add(8);
    toRemove.add(9);
    toRemove.add(13);
    toRemove.add(22);
    toRemove.add(55);
    toRemove.add(88);
    ArrayList<Integer> al=new ArrayList<>();
    for(int i=0;i<100;i++){
        al.add(i);
    }
    al.removeAll(toRemove);