Java program to find missing and additional values in two lists

JavaObject Oriented ProgrammingProgramming

To find missing and additional values in two lists, the Java program is as follows −

Example

 Live Demo

import java.util.*;
public class Demo{
   public static void main(String[] args){
      List my_list_1 = new ArrayList();
      List my_list_2 = new ArrayList();
      my_list_1.add(new Integer("101"));
      my_list_1.add(new Integer("90"));
      my_list_1.add(new Integer("34"));
      my_list_2.add(new Integer("34"));
      my_list_2.add(new Integer("67"));
      my_list_2.add(new Integer("90"));
      for(int i = 0; i < my_list_1.size(); i++){
         if (my_list_2.contains(my_list_1.get(i)))
         continue;
            else
         System.out.println("The missing element is : "+my_list_1.get(i));
      }
      for(int j=0; j<my_list_2.size();j++){
         if (my_list_1.contains(my_list_2.get(j)))
         continue;
            else
         System.out.println("The new element in the list is : "+my_list_2.get(j));
      }
   }
}

Output

The missing element is : 101
The new element in the list is : 67

A class named Demo contains the main function and two array lists are created inside it. Elements are added to both the array lists using the ‘add’ function. A ‘for’ loop is used to iterate over the first array list and next, the second array list is checked to contain the elements of the first array list. If that condition is true, then the execution continues. Otherwise, the missing element is figured out and displayed on the console. Similarly, to check if an additional element that is not present in the first list is present in the second list, the second list is iterated over using the ‘for’ loop and the extra element (if any) is figured out and displayed on the console.

raja
Published on 07-Jul-2020 12:00:26
Advertisements