简体   繁体   English

Java Streams方法不影响我的ArrayList吗?

[英]Java Streams methods not affecting my ArrayList?

I'm trying to perform the following stream operations on an ArrayList named parts : 我正在尝试对名为parts的ArrayList执行以下流操作:

parts
    .stream()
    .map(t -> t.toLowerCase())
    .distinct()
    .sorted()
    .collect(Collectors.toList());

where parts contains Strings like this: 其中parts包含这样的字符串:

Adventures
in
Disneyland
Two
blondes
were
going
to
Disneyland
....

Except upon looking at the debugger, parts isn't changed at all. 除了查看调试器外,其他parts完全没有更改。 Not sure if I'm missing some step of the process? 不确定我是否缺少该过程的某些步骤?

upon looking at the debugger, "parts" isn't changed at all 在查看调试器时,“部件”完全没有改变

Correct. 正确。 Streams don't modify the elements of the collection that was used to create the stream. 流不修改用于创建流的集合的元素。 The stream is ultimately returning a new List that contains the mapped items. 该流最终将返回一个包含映射项的 List Just create a variable and assign the return value of your stream operations to it: 只需创建一个变量并为其分配流操作的返回值即可:

List<String> modifiedList = parts.stream()
    .map(t -> t.toLowerCase())
    .distinct()
    .sorted()
    .collect(Collectors.toList());

You are not storing the collected list anywhere. 您不在任何地方存储收集的列表。 Streams don't change the collection in-place. 流不会就地更改集合。

You should do: 你应该做:

parts = parts.stream().....;

Edit based on comments: 根据评论进行编辑

To get an ArrayList as opposed to any List , change your collector to: 要获取ArrayList而不是任何List ,请将您的收集器更改为:

.collect(Collectors.toCollection(ArrayList::new));

A stream does not alter the source of the stream so you are observing expected behaviour. 流不会改变流的来源,因此您正在观察预期的行为。

You should capture the result of your stream processing and inspect that in your debugger, eg. 您应该捕获流处理的结果,并在调试器中对其进行检查,例如。

List<String> result = parts.stream()...

This will create a new list and is how the map operator works. 这将创建一个新列表,这就是地图运算符的工作方式。 You are replacing the items in the stream with new objects and then you collect the stream into a new list. 您正在用新对象替换流中的项目,然后将流收集到新列表中。

You have to assign the result to the new list. 您必须将结果分配给新列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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