Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List difference in java

Tags:

java

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

like image 576
learn_plsql Avatar asked Dec 03 '10 19:12

learn_plsql


People also ask

How do I compare two lists in Java and get differences?

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.

How do I compare two lists in Java?

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.

What is the difference between a list and a Set in Java?

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.

Is list and ArrayList difference in Java?

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.


2 Answers

As an alternative, you could use CollectionUtils from Apache commons library. It has static intersection, union and subtract methods suitable for your case.

like image 164
barti_ddu Avatar answered Oct 04 '22 19:10

barti_ddu


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.

like image 38
Adam Avatar answered Oct 04 '22 20:10

Adam