Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set union and intersection using java streams

I currently have a java program that uses nested for loops to compute the union and intersection of a list of set of integers. How to do this using java parallel streams ? The code i have currently is as follows

for(Set<Integer> x : listA) {
  for (Set<Integer> y : listB) {
       Set u = Sets.union(x,y); // Uses Guava library
       Set i = Sets.intersection(x,y);
  }
}

I would like to make this fast as listA and listB are large.

like image 457
Ramesh K Avatar asked Oct 15 '25 14:10

Ramesh K


1 Answers

Intersection:

List<T> intersect = list1.stream()
                         .filter(list2::contains)
                         .collect(Collectors.toList());

Union:

List<T> union = Stream.concat(list1.stream(), list2.stream())
                                    .distinct()
                                    .collect(Collectors.toList());  
like image 191
Ali Azim Avatar answered Oct 17 '25 04:10

Ali Azim