0

I have two array lists listA and listB which may or may not contain same elements. For Example:

listA= [1,2,3] &
listB=[2,3,4]

I need to compare the two array lists and add the element which is present in listA and not in listB to listB. Also if any other element which is present in listB is not there in listA, I should delete it from listB.

Please help me how to code for this in Java.

I prefer using Iterator method if needed.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
Deepthi
  • 1
  • 1
  • 1

3 Answers3

1

Your description suggests you want to be working with sets. For example, say an element is in A twice but only in B once. Should it be added to B once?

The simplest answer to your question is to

List listA = ...
List listB = ...

listB.clear();
listB.addAll(listA);

however assuming you want to preserve some order you can do.

List listA = ...
List listB = ...
Set setA = new HashSet(listA);
setA.removeAll(listB);

Set setB = new HashSet(listB);
setB.removeAll(listA);

listB.addAll(setA);
listB.removeAll(setB);

Note: this will not add entries if A of an element has more than B and it will not remove entries if B has more of an element than A.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

Try this

for(int i : listA)
    if(!listB.contains(i)) listB.add(i);
for(int j : listB)
    if(!listA.contains(j)) listB.remove(j);

Otherwise

Arrays.sort(listA); Arrays.sort(listB);
for(int i = 0; i < listA.length(); i++)
{
   if(!listB.contains(listA.get(i))) listB.add(listA.get(i));
   if(!listA.contains(listB.get(i))) listB.remove(listA.get(i));
}
Shark
  • 6,513
  • 3
  • 28
  • 50
0

Simple steps for writing the code

First perform the deletion

   Iterate ListB
    For each element in ListB, check if it is present in List A
      If Not, delete from ListB
      else continue
 Close your loops

Then Addition

Iterate ListA
  For each element in ListA, check if it is present in List B
    If Not, add to ListB
    else continue
Close your loops

Sample Code:

    List<Integer> listA = ..
    List<Integer> listB = ..

    for(Integer intB: listB)
      if(!listA.contains(intB)){
         listB.remove(intB);
      }
    }   

   for(Integer intA: listA)
      if(!listB.contains(intA)){
         listB.add(intA);
      }
    }   
Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73