[英]Java Stream : Create new List from 2 Lists keeping only matching values
I'm working with java streams and I have an issue. 我正在使用Java流,但遇到了问题。 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: 但是,正如@Holger指出的那样,如果列表很大,则此解决方案可能效率不高,因此请尝试:
newList.retainAll(new HashSet<>(list2));
You have a stream answer in the comments. 您在评论中有一个流式答案。
You can also utilize the retainAll
method to achieve this. 您还可以利用
retainAll
方法来实现这一点。
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]
在此示例中,
newArr
将为[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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.