5

Is there a way in Java 8 to transform an Array/Collection using map() without having to reassign the created copy, e.g.

Arrays.stream(array).mapInPlace(x -> x / 100);
list.stream().mapInPlace(e -> e.replaceAll(" ", ""));

instead of

array = Arrays.stream(array).map(x -> x / 100).toArray();
list = list.stream().map(e -> e.replaceAll(" ", "")).collect(Collectors.toList());

?

If not, what's the reason for this design decision?

1
  • And you also have Map.replaceAll Commented Sep 5, 2018 at 13:34

1 Answer 1

9

Maybe using List::replaceAll in your case can help you :

Arrays.asList(array).replaceAll(x -> x / 100);

and

list.replaceAll(e -> e.replaceAll(" ", ""));

Ideone demo


Good point from @Holger, in case you need the index you can use Arrays::setAll :

Arrays.setAll(array, x -> array[x] / 100);

Or more better if you want your job to be in parallel you can use Arrays::parallelSetAll :

Arrays.parallelSetAll(array, x -> array[x] / 100);
Sign up to request clarification or add additional context in comments.

2 Comments

…and in case you need the index, Arrays.setAll​(array, index -> expression);
Thank you @Holger this is nice trick even we can use parallelSetAll

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.