CopyOnWriteArrayList provides a new method
public int addAllAbsent(Collection<? extends E> c) , which adds all of the elements in the specified collection that are not already contained in this list, to the end of this list. This is helpful when you need to add only unique elements into your list.
addAllAbsent(Collection extends E> c) returns an int – the number of elements that are added from the given collection.
Sample Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
package com.kscodes.collections.samples; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; public class CopyOnWriteArrayListAddAllIfAbsentEx { public static void main(String[] args) { // Create a copyOnWriteArrayList object CopyOnWriteArrayList<String> copyOnWriteArrayList = new CopyOnWriteArrayList<>(); // Adding 4 elements using add() method copyOnWriteArrayList.add("Zero"); copyOnWriteArrayList.add("One"); copyOnWriteArrayList.add("Two"); copyOnWriteArrayList.add("Three"); copyOnWriteArrayList.add("Four"); // Printing the added elements System.out.println("Original Contents :: " + copyOnWriteArrayList); // Create a new ArrayList and add few contents that are similar to // copyOnWriteArrayList and few new contents List<String> arrayList = new ArrayList<>(); arrayList.add("One"); arrayList.add("Five"); arrayList.add("Six"); arrayList.add("Zero"); // Now use addAllIfAbsent method. Only new contents will be added in // copyOnWriteArrayList int totalElementsAdded = copyOnWriteArrayList.addAllAbsent(arrayList); // Again printing the elements to see if the elements were added System.out.println("New Modified contents :: " + copyOnWriteArrayList); System.out.println("Total Elements added from new List :: " + totalElementsAdded); } } |
Output
In the code above, we added a new collection that included – “One”, “Five”, “Six” and “Zero” to the copyOnWriteArrayList. Since CopyOnWriteArrayList already had “Zero” and “One”, it did not add it again. Only the other elements were added.