Union and Intersection of ArrayList in Java


Intersection

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main
{

	public static void main(String[] args)
	{
		
		 List<String> list1 = new ArrayList<String>(Arrays.asList("A", "B", "C"));
	     List<String> list2 = new ArrayList<String>(Arrays.asList("B", "C", "D", "E", "F"));
	      
	      list1.retainAll(list2) ;
	      	      
	      System.out.println(list1);
	      System.out.println(list2);	     
	}
}
[B, C]
[B, C, D, E, F]

Union

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main
{

	public static void main(String[] args)
	{
		
		 List<String> list1 = new ArrayList<String>(Arrays.asList("A", "B", "C"));
	     List<String> list2 = new ArrayList<String>(Arrays.asList("B", "C", "D", "E", "F"));
	      
	      list1.addAll(list2) ;
	      	      
	      System.out.println(list1);
	      System.out.println(list2);	     
	}
}
[A, B, C, B, C, D, E, F]
[B, C, D, E, F]