Skip to content

Instantly share code, notes, and snippets.

@pbesra
Last active October 15, 2023 17:03
Show Gist options
  • Save pbesra/243108503a08002e40055d3764892590 to your computer and use it in GitHub Desktop.
Save pbesra/243108503a08002e40055d3764892590 to your computer and use it in GitHub Desktop.
union, intersection, difference in java (over a set)
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Set<Integer> s1=new HashSet<>();
Set<Integer> s2=new HashSet<>();
s1.addAll(Arrays.asList(new Integer[] {1,19,17,10,4,5}));
s2.addAll(Arrays.asList(new Integer[] {10, 1, 45,17, 13, 15}));
s1.addAll(s2);
Set<Integer> union=new HashSet<>(s1);
union.addAll(s2);
System.out.println("union : ");
System.out.println(union);
Set<Integer> intersection=new HashSet<>(s1);
intersection.retainAll(s2);
System.out.println("intersection : ");
System.out.println(intersection);
System.out.println("difference : ");
Set<Integer> difference=new HashSet<>(s1);
difference.removeAll(s2);
System.out.println(difference);
}
}
@JAIMIN05
Copy link

JAIMIN05 commented Oct 15, 2023

intersection means common element in 2 array,
but your output is wrong ,
your intersection output is :- [1,17,10, 45, 13, 15]
correct output is:-[1,17,10]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment