HashimR
HashimR

Reputation: 3833

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];

Upvotes: 5

Views: 339

Answers (2)

Ruslan
Ruslan

Reputation: 6290

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); 

Upvotes: 12

Eran
Eran

Reputation: 393801

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;
                                  });

Upvotes: 4

Related Questions