1

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

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
venkat
  • 465
  • 3
  • 9

4 Answers4

3

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);
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
2
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); 
André Schild
  • 4,592
  • 5
  • 28
  • 42
venkat
  • 465
  • 3
  • 9
1
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.

adickinson
  • 553
  • 1
  • 3
  • 14
  • "i want fetch the duplicate elements and remove it from arraylist" -> I'm confused, you asked here to remove duplicate elements, did you mean to remove BOTH values if more than one for a given number exists? – adickinson Oct 16 '18 at 09:14
0

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);
Dark Knight
  • 8,218
  • 4
  • 39
  • 58