简体   繁体   中英

Java Streams methods not affecting my ArrayList?

I'm trying to perform the following stream operations on an ArrayList named parts :

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

where parts contains Strings like this:

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

Except upon looking at the debugger, parts isn't changed at all. 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. 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:

.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.

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