Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to modify all elements of a list in java?

I have a list of Strings and I want to perform the same operation on all of the Strings in the list.

Is it possible without performing a loop?

like image 496
AAaa Avatar asked Jun 14 '11 15:06

AAaa


People also ask

Can we modify list in Java?

You can replace an element of an ArrayList using the set() method of the Collections class. This method accepts two parameters an integer parameter indicating the index of the element to be replaced and an element to replace with.

Can we modify list while iterating in Java?

The Best Answer is At the end the whole list will have the letter "D" as its content. It's not a good idea to use an enhanced for loop in this case, you're not using the iteration variable for anything, and besides you can't modify the list's contents using the iteration variable.

Can you modify an ArrayList?

You can modify an ArrayList elementarily (Only one element is added or removed or updated) or in bulk (More than one elements are added or removed or updated).


2 Answers

Well something's got to loop, somewhere - if you want to abstract that into your own method, you could do so, but I don't believe there's anything built into the framework.

Guava has various methods in Iterables to perform projections etc, but if you want to modify the list on each step, I'm not sure there's any support for that. Again, you could write your own method (extremely simply) should you wish to.

When Java eventually gets closures, this sort of thing will become a lot more reasonable - at the moment, specifying the "something" operation is often more effort than it's worth compared with hard-coding the loop, unfortunately.

like image 158
Jon Skeet Avatar answered Oct 21 '22 04:10

Jon Skeet


You could do it recursively, but I don't see why you'd want to. You may be able to find something similar to Python's map function (which, behind the scenes, would either be a loop or a recursive method)

Also note that strings are immutable - so you'll have to create 'copies' anyway.

like image 31
dfb Avatar answered Oct 21 '22 05:10

dfb