Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intersection between nested lists java 8 streams

I have a nested list of Long. for example:

List<List<Long>> ids = [[1,2,3],[1,2,3,4],[2,3]];

Is there a way using streams to create a new list of items that are present in all the lists:

List<Long> result = [2,3];
like image 378
HashimR Avatar asked Feb 18 '19 11:02

HashimR


2 Answers

There is quite concise solution without stream:

List<Long> result = new ArrayList<>(ids.get(0));
ids.forEach(result::retainAll);

System.out.println(result);

Update: as it was mentioned in the comments by @ernest_k to avoid the superfluous retainAll() call you can get sublist before:

ids.subList(1, ids.size()).forEach(result::retainAll); 
like image 106
Ruslan Avatar answered Oct 06 '22 01:10

Ruslan


Here's a (less concise) Stream version using reduce:

List<Long> intersect = ids.stream()
                          .reduce(ids.get(0),
                                  (l1,l2) -> {
                                      l1.retainAll(l2);
                                      return l1;
                                  });

Or (if we want to avoid mutating the original Lists):

List<Long> intersect = ids.stream()
                          .reduce(new ArrayList<>(ids.get(0)),
                                  (l1,l2) -> {
                                      l1.retainAll(l2);
                                      return l1;
                                  });
like image 28
Eran Avatar answered Oct 06 '22 01:10

Eran