Pin It

How to perform operations of Union and Intersection on two or more LinkedList in Java ?.

Program to demonstrate Union and Intersection of two LinkedList in Java

package com.hubberspot.collections.example;

import java.util.*;
import java.io.*;

public class LinkedListOperationsDemo
{
  static BufferedReader br = new BufferedReader
   (new InputStreamReader(System.in));

  public static void main(String args[]) throws IOException
  {
    LinkedList list1 = new LinkedList();
    LinkedList list2 = new LinkedList();
    LinkedList list3 = new LinkedList();
    LinkedList list4 = new LinkedList();
   
    int num1, num2;

    System.out.print("Enter no.of Elements in list 1:");
  
    num1 = Integer.parseInt(br.readLine());

    System.out.println("Enter Elements of list 1");
  
    for(int i=1; i <= num1; i++)
    {
      System.out.print("Enter Element "+i+": ");
      String element = br.readLine();
 
      if(!list1.contains(element))
 list1.add(element);
    }                                

    System.out.print("Enter no.of Elements in list 2:");
  
    num2 = Integer.parseInt(br.readLine());
  
    System.out.println("Enter Elements of list 2");
  
    for(int i=1; i <= num2; i++)
    {
      System.out.print("Enter Element "+i+": ");
      String element = br.readLine();
 
      if(!list2.contains(element))
 list2.add(element);
    }                                

    Collections.sort(list1);
    Collections.sort(list2);

    System.out.println("List 1:"+list1);
    System.out.println("List 2:"+list2);
     
    for(int i=0; i < list1.size(); i++)
      list3.add(list1.get(i));
  
    for(int i=0; i < list2.size(); i++)
      if(!list1.contains(list2.get(i)))
 list3.add(list2.get(i));
  
    System.out.println("Union: "+list3);
  
    for(int i=0; i < list1.size(); i++)
       list4.add(list1.get(i));
  
    list4.retainAll(list2);
  
    System.out.println("Intersection: "+list4);

   }
}
Output of the program : 

 
Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot