2

I have two lists (ArrayList) in java .

The values of list1 = [1,2,3]

the values of list2 = [2,3,4]

The program's output should say '1' is missing and '4' is a new element . How do we go about doing that ?

Vinoth Kumar C M
  • 10,378
  • 28
  • 89
  • 130
  • 1
    See this for reference: http://stackoverflow.com/questions/23445/how-best-to-compare-two-collections-in-java-and-act-on-them – dertkw May 04 '11 at 05:04
  • If your arrays are known to be sorted, you can do a single pass solution... so please give additional details if you are looking for something faster/more efficient than copying into a Set. – Dilum Ranatunga May 04 '11 at 05:36

3 Answers3

8

Just use Sets and the removeAll method,

Set missing = new HashSet(list1);
missing.removeAll(list2);
System.out.println("missing:" + missing);

Set extra = new HashSet(list2);
extra.removeAll(list1);
System.out.println("extra:" + extra);
sbridges
  • 24,960
  • 4
  • 64
  • 71
0

I believe we can pick first element and iterate through the 2nd list and check if the element is available if its there in the second list skip and pick next element of the first list. And repeat for the extra element logic too. Just i am worried about complexity! If we want to use collections then it might be even easier. But I think using plane arrays might be better!

This should help:

 for (int i = 0; i < list1.size(); i++) {
      if (list2.contains(list1.get(i))) 
     return;
      else
    S.o.p("missing:"+list1.get(i));
      }
 for (int j=0; j<list2.size();j++){
      if (list1.contains(list2.get(j))) 
     return;
      else
    S.o.p("new element:"+list1.get(j));

    } 
java_enthu
  • 2,279
  • 7
  • 44
  • 74
  • Why the `return`? You need to carry on looping until you've exhausted the list. Plus this is an O(n^2) algorithm, which is fine for small lists but will quickly exhaust your patience if the lists are large. – Simon Nickerson May 04 '11 at 05:22
0
  import java.util.*;      

  class Demo{      
     public static void main(String ...args){      
         List list1 = new ArrayList();       
         List list2 = new ArrayList();      

         list1.add(new Integer("1"));     
         list1.add(new Integer("2"));      
         list1.add(new Integer("3"));           

         list2.add(new Integer("2"));      
         list2.add(new Integer("3"));     
         list2.add(new Integer("4"));     

         for(int i = 0; i < list1.size(); i++) {      
            if (list2.contains(list1.get(i)))                      
                continue;      
            else     System.out.println("missing:"+list1.get(i));       
         }     
         for(int j=0; j<list2.size();j++){     
            if (list1.contains(list2.get(j)))                  
                 continue;     
            else     System.out.println("new element:"+list2.get(j));              
         }        
  }      

}

deepakl.2000
  • 176
  • 1
  • 4
  • 19