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

}
}
 


For more of such hot topics read my other posts here :

Visit my new website



Article Written By jontymagicman

I am DInesh Varyani.

Last updated on 26-07-2016 274 0

Please login to comment on this post.
There are no comments yet.
How To Create A Simple Frame Using Swing Api In Java?.
Creating And Running A Thread Using Runnable Interface