Write a Java program to compare two array lists


This is a Java program that compares two ArrayLists of Strings and prints the result of the comparison. Here's how the program works:

  • The program creates two ArrayLists of Strings, named list_str1 and list_str2, and initializes them with some values.
  • The program prints the contents of both ArrayLists using System.out.println.
  • The program creates a third ArrayList of Strings, named list_str3.
  • The program uses a for-each loop to iterate over the elements of list_str1.
  • For each element in list_str1, the program checks if that element is also present in list_str2 using the contains method.
  • If the element is present in list_str2, the program adds the String "True" to list_str3.
  • If the element is not present in list_str2, the program adds the String "False" to list_str3.
  • The program prints the contents of list_str3 using System.out.println.

Source Code

import java.util.*;
public class Compare_TwoArrayList
{
	public static void main(String[] args)
	{
		ArrayList<String> list_str1= new ArrayList<String>();
		list_str1.add("Computer");
		list_str1.add("Keyboard");    
		list_str1.add("Mouse");
		list_str1.add("CPU");
		list_str1.add("Printer");
		list_str1.add("Derive");
		ArrayList<String> list_str2 = new ArrayList<String>();
		list_str2.add("Printer");
		list_str2.add("Mouse");
		list_str2.add("Keyboard");		
		System.out.println("String 1 :" + list_str1);
		System.out.println("String 2 :" + list_str2);
		ArrayList<String> list_str3 = new ArrayList<String>();
		for (String e : list_str1)
		list_str3.add(list_str2.contains(e) ? "True" : "Flase");
		System.out.println("Compare String 1 & 2 :"+list_str3);
	}
}

Output

String 1 :[Computer, Keyboard, Mouse, CPU, Printer, Derive]
String 2 :[Printer, Mouse, Keyboard]
Compare String 1 & 2 :[Flase, True, True, Flase, True, Flase]

Example Programs