venkat
venkat

Reputation: 475

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

Upvotes: 1

Views: 592

Answers (4)

venkat
venkat

Reputation: 475

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

Upvotes: 2

Ori Marko
Ori Marko

Reputation: 58772

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

Upvotes: 3

adickinson
adickinson

Reputation: 553

ArrayList<Integer> withoutDuplicates = new ArrayList<>(new HashSet<>(al));

Does not affect the original list with duplicates, which is what you seem to be asking for. If you do not care about the structure used for the second collection you could just keep it as a Set without creating another ArrayList.

Upvotes: 1

Dark Knight
Dark Knight

Reputation: 8347

Make use of streams to get distinct value. However i still believe Sets perfectly suit this scenario.

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

    List<Integer> list = al.stream().distinct().collect(Collectors.toList());
System.out.println(list);

Upvotes: 0

Related Questions