rav
rav

Reputation: 241

Compare two list and output missing and extra element in Java

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.

  1. Read element from A.
  2. Check if element exists in B.
  3. If no add it to Extra list.
  4. If yes remove the element from both A and B.
  5. If B is empty add all renaming elements in Extra list.
  6. If A is empty add all renaming elements in Missing list.

Upvotes: 4

Views: 9044

Answers (1)

Alexandru Somai
Alexandru Somai

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:

  1. 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 is O(1) compared to O(n) for a list, therefore you should never use a list if you often need to run contains.


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

Related Questions