-1

I'm working with java streams and I have an issue. I have a List like:

[1,2,3,4,5]

and another like:

[1,3,5,7,9]

My question is how can I create a new list like:

[1,3,5]

Thanks.

DMcg
  • 129
  • 3
  • 11
  • https://docs.oracle.com/javase/8/docs/api/java/util/List.html#retainAll-java.util.Collection-, https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#filter-java.util.function.Predicate- – JB Nizet Jul 11 '18 at 13:34
  • 3
    `list1.stream().filter(i -> list2.contains(i)).collect(Collectors.toList());` – Youcef LAIDANI Jul 11 '18 at 13:34
  • 3
    As @YCF_L has shown, but if the lists get large, I’d use `list1.stream().filter(new HashSet<>(list2)::contains).collect(Collectors.toList());` instead, to avoid *n×m* time complexity. – Holger Jul 11 '18 at 13:37
  • do you have any performance restrictions in terms of memory or runtime complexity? can streams be assumed to be sorted? – hgrey Jul 11 '18 at 13:37
  • This is a really nice trick @Holger – Youcef LAIDANI Jul 11 '18 at 13:41
  • Possible duplicate of: https://stackoverflow.com/questions/31683375/java-8-lambda-intersection-of-two-lists – Ravindra Ranwala Jul 11 '18 at 13:41

3 Answers3

4

There is a much simpler way than using a stream here:

List<Integer> newList = new ArrayList<>(list1);
newList.retainAll(list2);

However, as pointed out by @Holger, if the lists are large, this solution can be inefficient, so instead try:

newList.retainAll(new HashSet<>(list2));

You have a stream answer in the comments.

achAmháin
  • 4,176
  • 4
  • 17
  • 40
2

You can also utilize the retainAll method to achieve this.

 ArrayList<Integer> newArr = new ArrayList<>(arr);   //Create a new List based off the first list
 newArr.retainAll(arr2);   //Retain only the elements in the first list and second list

In this example newArr would be [1,3,5]

GBlodgett
  • 12,704
  • 4
  • 31
  • 45
1

If you have lists

List l1 = ..., List l2 = ...

You can do:

List result = l1.stream().filter(x -> l2.contains(x)).collect(Collectors.toList());
Hongyu Wang
  • 378
  • 1
  • 10