使用Stream“过滤器”和“收集”后,Java 8会创建一个新列表吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34667561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:11:07  来源:igfitidea点击:

Will Java 8 create a new List after using Stream "filter" and "collect"?

javalistjava-8java-stream

提问by coderz

I have code using Java8:

我有使用 Java8 的代码:

List<Integer> list = new ArrayList<Integer>();
list.add(3);
list.add(5);
list.add(4);
list.add(2);
list.add(5);
list = list.stream().filter(i -> i >= 3).collect(Collectors.toList());

Original list is [3, 5, 4, 2, 5]. After "filter" and "collect" operation, the list changes to [3, 5, 4, 5].

原始列表是 [3, 5, 4, 2, 5]。经过“过滤”和“收集”操作后,列表变为[3, 5, 4, 5]。

Are all the operations perform on original list and does not create a new list? Or after "filter" and "collect" operation, return a new created list and ignore original list?

所有操作都在原始列表上执行并且不创建新列表吗?或者在“过滤”和“收集”操作之后,返回一个新创建的列表并忽略原始列表?

回答by Mureinik

The call to collectwith Collectors.toList()will create a new list. The original list is not effected by the streaming.

collectwith的调用Collectors.toList()将创建一个新列表。原始列表不受流媒体影响。

回答by Tagir Valeev

If you actually want to modify the original list, consider using removeIf:

如果您确实想修改原始列表,请考虑使用removeIf

list.removeIf(i -> i < 2);

回答by Chris

Stream operations are either intermediate or terminal. Intermediate operationsreturn a stream so you can chain multiple intermediate operations. Terminaloperations return void or something else.

流操作要么是中间的,要么是终端的。 中间操作返回一个流,因此您可以链接多个中间操作。 终端操作返回 void 或其他东西。

Most of stream operations are non-interfering, it means that they don't modify the data source of the stream. But by calling the collectmethod you are creating a new list and you're assigning it to list

大多数流操作是无干扰的,这意味着它们不会修改流的数据源。但是通过调用该collect方法,您正在创建一个新列表并将其分配给list

回答by David Pérez Cabrera

Try this:

试试这个:

List<Integer> list = new ArrayList<Integer>();
list.add(3);
list.add(5);
list.add(4);
list.add(2);
list.add(5);
List<Integer> list2 = list.stream().filter(i -> i >= 3).collect(Collectors.toList());
System.out.println("list:  "+list);
System.out.println("list2: "+list2);

回答by Jason.chen

Referring to Guava Lists.transform() function will help you understand why a new list needs to generate. Before JDK 7, Lists.transform() function is strongly recommended to implement similar feature.

参考 Guava Lists.transform() 函数将帮助您理解为什么需要生成新列表。在 JDK 7 之前,强烈建议使用 Lists.transform() 函数来实现类似的功能。