Skip to content

Instantly share code, notes, and snippets.

@ylegall
Last active December 28, 2015 06:29
Show Gist options
  • Save ylegall/7457883 to your computer and use it in GitHub Desktop.
Save ylegall/7457883 to your computer and use it in GitHub Desktop.
Compute the intersection of a collection of sets
import java.io.*;
import java.util.*;
public class Intersect {
static Set<Integer> intersection(List<Set<Integer>> sets) {
Set<Integer> s1 = sets.get(0);
List<Integer> removeList = new ArrayList<>();
for (int s = 1; s < sets.size(); ++s) {
for (int i : s1) {
if (!(sets.get(s).contains(i))) removeList.add(i);
}
for (int i : removeList) s1.remove(i);
removeList.clear();
}
return s1;
}
public static void main(String[] args) {
Set<Integer> s1 = new HashSet<>(Arrays.asList(1,3,5,7,9));
Set<Integer> s2 = new HashSet<>(Arrays.asList(5,8,9,7,1));
Set<Integer> s3 = new HashSet<>(Arrays.asList(0,5,-4,88,7));
Set<Integer> s4 = new HashSet<>(Arrays.asList(3,1,5,13,7,2));
List<Set<Integer>> sets = Arrays.asList(s1,s2,s3,s4);
System.out.println(intersection(sets));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment