Updating an array of strings using a java stream

I know that for an object, we can collect and update the object for the collection at our discretion, but for immutable objects, such as strings, how can we update the array with a new object without converting it to an array again.

For example, I have an array of strings. I want to iterate over each row and crop it. Otherwise, I would have to do something like this:

Arrays.stream(str).map(c -> c.trim()).collect(Collectors.toList())

In the end, I will get List, not String [], which I originally gave. Its a lot of processing. Is there a way to do something similar to:

for(int i = 0; i < str.length; i++) {
        str[i] = str[i].trim();
    }

using java threads?

+4
source share
3 answers

, . Java API Stream API.

Alexis C. , Arrays.setAll(arr, i -> arr[i].trim());

Theres parallelSetAll, , .

, Arrays.asList(arr).replaceAll(String::trim);.

, , Arrays.asList, List. .

+8

toArray:

str = Arrays.stream(str).map(c -> c.trim()).toArray(String[]::new);

( Java 7) , .

, Stream s, , :

IntStream.range (0, str.length).forEach (i -> {str[i] = str[i].trim();});
+3

Not as much processing as you might think, the array has a known size, and the separator from it will be SIZED, so the resulting collection size will be known before processing, and the space for it can be allocated ahead of time, without having to resize the collection.

It is also always interesting that in the absence of real tests, we almost always assume that it is slow or hungry.

Of course, if you want to get an array, there is a way to do this:

 .toArray(String[]::new);
+2
source

Source: https://habr.com/ru/post/1663830/


All Articles