Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 - Map an Array/Collection in place

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?

like image 592
Doopy Avatar asked Sep 05 '18 10:09

Doopy


1 Answers

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);
like image 132
YCF_L Avatar answered Sep 22 '22 16:09

YCF_L