简体   繁体   中英

Java Stream : Create new List from 2 Lists keeping only matching values

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.

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.

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]

If you have lists

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

You can do:

List result = l1.stream().filter(x -> l2.contains(x)).collect(Collectors.toList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM