Last active
October 15, 2023 17:03
-
-
Save pbesra/243108503a08002e40055d3764892590 to your computer and use it in GitHub Desktop.
union, intersection, difference in java (over a set)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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]