I have two ArrayList<Integer>
as follows:
original: 12, 16, 17, 19, 101
selected: 16, 19, 107, 108, 109
I want to do difference on these lists such that in the end I have two lists:
Add: 108,109,107
remove: 12, 17, 101
Length of original and selected lists varies and one can be greater/smaller than the other
Using the Java List API. We can create a copy of one list and then remove all the elements common with the other using the List method removeAll(): List<String> differences = new ArrayList<>(listOne); differences. removeAll(listTwo); assertEquals(2, differences.
Java provides a method for comparing two Array List. The ArrayList. equals() is the method used for comparing two Array List. It compares the Array lists as, both Array lists should have the same size, and all corresponding pairs of elements in the two Array lists are equal.
List is an ordered sequence of elements. User can easily access element present at specific index and can insert element easily at specified index. Set is an unordered list of elements. Set does not have duplicate elements.
List interface is used to create a list of elements(objects) that are associated with their index numbers. ArrayList class is used to create a dynamic array that contains objects. List interface creates a collection of elements that are stored in a sequence and they are identified and accessed using the index.
As an alternative, you could use CollectionUtils from Apache commons library. It has static intersection, union and subtract methods suitable for your case.
List<Integer> original = Arrays.asList(12,16,17,19,101); List<Integer> selected = Arrays.asList(16,19,107,108,109); ArrayList<Integer> add = new ArrayList<Integer>(selected); add.removeAll(original); System.out.println("Add: " + add); ArrayList<Integer> remove = new ArrayList<Integer>(original); remove.removeAll(selected); System.out.println("Remove: " + remove);
Output:
Add: [107, 108, 109] Remove: [12, 17, 101]
Uses Collection's removeAll method. See javadocs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With