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];
                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); 
                        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;
                                  });
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With