简体   繁体   English

Java Stream:从2个列表创建新列表,仅保留匹配值

[英]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.

相关问题 使用Java 8流在2个列表中查找匹配的元素,并从另一个列表中更新一个列表值 - Find element matching in 2 lists using java 8 stream and updating one list value from the other 从Java中的列表创建列表 - create lists from list in java new Java对象列表,匹配另外两个列表中的条目 - new Java List of objects by matching entries in two other lists 使用java 8流在2个列表中查找元素匹配 - Find element matching in 2 lists using java 8 stream 如何使用 java stream 从现有列表中转换创建的新匹配值列表 - how to convert created new list of matched values from existing list using java stream 从流中的两个列表创建隔离值的映射 - Create map of segregated values from two lists in stream 替换 Java 8 中地图列表中的值 - Replace values in a List of Lists from a Map in Java 8 如何从多个列表中创建匹配对象列表并删除匹配列表中的对象,使其反映在原始列表中 - How to create a list of matching objects from multiple lists and delete objects in the matching list such that it reflects in the original list 从文件中读取值并在 Java 中使用流将它们拆分为两个列表 - Reading values from a file and splitting them into two lists with stream in Java 列表上的流过滤器保留了一些过滤后的值 - Stream filter on list keeping some of the filtered values
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM