Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach can not manipulate a String list?

I found this thread on the topic and I wondered why it's so hard in Java to replace a value in a List.

My code looks ugly like this:

    List<String> stringList = new ArrayList<>();
    // ... add some elements
    for (int i = 0; i< stringList.size(); ++i) {
        if (stringList.get(i).contains("%")) {
            stringList.set(i, stringList.get(i).replace("%", backupStorePath));
        }
    }

Is this really the only way to do this? Why can't I use a foreach loop?

for (String command : stringList) {
    command = command.replace("%", backupStorePath);
}

This must be a java's "Copy by value" problem and String being immutable, but why was it implemented like that? Why is command a copy of the original reference and not the original itself?

like image 693
codepleb Avatar asked Jan 23 '26 05:01

codepleb


1 Answers

Since Java-8 you have a new option to use List.replaceAll:

stringList.replaceAll(command -> command.replace("%", backupStorePath));

Note that for loop works for any Iterable, not only List. And most of other iterables do not support the element replacement. So even if Java designers had decided to support modifications, it would be necessary to separate List and non-List cases which would certainly add some complexity.

like image 131
Tagir Valeev Avatar answered Jan 24 '26 20:01

Tagir Valeev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!