user10303165
user10303165

Reputation:

Find items if not equal between lists

I Have 2 ArrayList in my project. I want to get items which is not equal.

For Example:

LIST 1 - LIST 2

AB ------- AB

BA ------- BA

CC

I wanna get this CC. I'm doing like this:

ArrayList<String> alllist= new ArrayList<>(ArrayList<String> 1);
for (String i : ArrayList<String> 1) {
                for (String j :  ArrayList<String> 2) {
                    if (i.equals(j)) {
                        alllist.remove(i);
                        break;
                    }
                }
            }

This work if I haved 3 or 4 items in ArrayList but when I add 200 items this method doesn't work fine and getting wrong list.

Any idea? what can I do more?

Thanks a lot.

Upvotes: 1

Views: 1711

Answers (3)

1218985
1218985

Reputation: 8012

If I understand your question correctly, you are looking for a symmetric difference. You can use CollectionUtils.disjunction from Apache Commons Collections

Given:

List<String> list1 = Arrays.asList("AB", "BA", "DD");
List<String> list2 = Arrays.asList("AB", "BA", "CC");

Action:

System.out.println(CollectionUtils.disjunction(list1, list2));

Result:

[DD, CC]

Upvotes: 2

Faiizii Awan
Faiizii Awan

Reputation: 1710

ArrayList<String> list2 = new ArrayList(); 
list2.add("AB");
list2.add("BA");
ArrayList<String> list1 = new ArrayList();
list1.add("AB");
list1.add("BA");
list1.add("C");
//remove all the element from the list1 which are also in list2 
list1.removeAll(list2);
System.out.println("Result: " + list1); //only C will left behind

Upvotes: 0

Gabe Sechan
Gabe Sechan

Reputation: 93559

If you need everything in list 1 but not list 2

1) Walk the first list and add each element to a HashSet.

2) use set.removeAll(list2) to remove everything in list 2.

The remainder is what's in list1 and not list2.

If you need to get everything in either list not in the other, you can repeat that in reverse. This should reverse the operation to O(n+m) where n is the length of list 1 and m is the length of list 2. Your pseudocode is O(n*m).

HashSet firstButNotSecond = new HashSet(list1);
firstButNotSecond.removeAll(list2);
HashSet secondButNotFirst = new HashSet(list2);
secondButNotFirst.removeAll(list1);

Upvotes: 1

Related Questions