Reputation: 241
I have two lists of strings List A and B.Lists might have same length or maybe one is longer than the other.There's no duplicate values in each list.They consist of random numbers.
What I want to do is to find the missing and the extra element exists in A compared to list B.And save them in two new lists , one for missing elements and one for extra elements.
For Example :
A = ["3000047" , "3000042" , "3000030" , "30000475"]
B = ["3000047" , "3000043" , "3000030" ]
The output should be
Missing = ["3000043"]
Extra = ["3000042" , "30000475"]
I think of doing at as below. But not sure about the performance and its efficiency.
Upvotes: 4
Views: 9044
Reputation: 1405
But not sure about the performance and its efficiency
Performance wise, use Set
(HashSet
implementation) instead of List
. This will give better O
time complexity at:
- Check if element exists in B.
This is when you'll apply contains
method. Check this answer for details on that.
Contains for a
HashSet
isO(1)
compared toO(n)
for a list, therefore you should never use a list if you often need to runcontains
.
The algorithm that you've proposed could be achieved using Java built-in functions.
Set#removeAll
Set<String> A = new HashSet<>(Arrays.asList("3000047", "3000042", "3000030", "30000475"));
Set<String> B = new HashSet<>(Arrays.asList("3000047", "3000043", "3000030"));
Set<String> copyA = new HashSet<>(A);
Set<String> copyB = new HashSet<>(B);
copyB.removeAll(A);
System.out.println("Missing: " + copyB);
copyA.removeAll(B);
System.out.println("Extra: " + copyA);
Output
Missing: [3000043]
Extra: [3000042, 30000475]
Upvotes: 8