Write a Java program to compare two linked lists


The Java code provided demonstrates how to compare two linked lists and create a third linked list indicating whether each element in the first linked list is present in the second linked list.

  • The code defines a class named Compare_TwoList with a main method, which serves as the entry point for the Java program.
  • Inside the main method, two LinkedList objects named b1_list and b2_list are created with a type parameter of String, indicating that they will store strings as their elements.
  • Strings such as "Java", "C", "Cpp", etc., are added to b1_list and b2_list using the add method, which appends the elements to the end of the lists.
  • The System.out.println statements are used to print the initial contents of b1_list and b2_list before any modifications.
  • Next, a new LinkedList object named b3_list is created to store the comparison results.
  • The for-each loop is used to iterate over b1_list, and for each element in b1_list, the b2_list.contains(e) method is called to check if the element is present in b2_list. If the element is present in b2_list, then "Yes" is added to b3_list; otherwise, "No" is added to b3_list using the ternary operator.
  • The System.out.println statement is used to print the contents of b3_list, which will indicate whether each element in b1_list is present in b2_list or not.
  • The output of the program will be the initial contents of b1_list and b2_list printed on the first two lines, followed by the elements of b3_list printed on the third line.

Source Code

import java.util.*;
public class Compare_TwoList
{
	public static void main(String[] args)
	{
		LinkedList<String> b1_list = new LinkedList<String>();
		b1_list.add("Java");
		b1_list.add("C");
		b1_list.add("Cpp");
		b1_list.add("Python");
		b1_list.add("Php");
		System.out.println(b1_list);   
		LinkedList<String> b2_list = new LinkedList<String>();
		b2_list.add("Cpp");
		b2_list.add("Html");
		b2_list.add("Php");
		b2_list.add("MySql");
		System.out.println(b2_list);  
		LinkedList<String> b3_list = new LinkedList<String>();
		for (String e : b1_list)
		{
			b3_list.add(b2_list.contains(e) ? "Yes" : "No");
		}
		System.out.println(b3_list);         
	}
}

Output

[Java, C, Cpp, Python, Php]
[Cpp, Html, Php, MySql]
[No, No, Yes, No, Yes]

Example Programs