简体   繁体   中英

Java :Comparing two lists

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?

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);

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));

    } 
  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));              
         }        
  }      

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM