Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a part of string in big array with replace method and Java 8

I have array String[] values = new String[100], and I need to check all strings from 10 to 35 with Java 8. Cause I don't want to do it with if and else.

For example:

for (int i = 10; i <= 35; i++){
    if (values[i].contains("something")) {
      values[i].replace("something", "something else");
    }
}

How can I do it with Java 8 and and small amount of code?

Help me please.

like image 490
noxi Avatar asked Oct 27 '25 12:10

noxi


2 Answers

Here's an alternative approach that might be a bit cleaner:

Arrays.asList(values).subList(10, 35 + 1)
      .replaceAll(s -> s.replace("something", "something else"));

NOTES:

  • subList() takes a half-open interval, hence the second argument has +1.

  • The result of String.replace() has to be assigned or returned, not thrown away, since of course it can't modify the original string.

  • There's no point in calling String.contains() since that's implemented in terms of String.indexOf(). One of the first things String.replace() does is to call String.indexOf() and bail out if the string isn't found.

like image 154
Stuart Marks Avatar answered Oct 29 '25 07:10

Stuart Marks


I can think of this, but it's not any more readable or effective than what you already have in place:

 IntStream.rangeClosed(10, 35)
            .forEach(ix -> values[ix] = values[ix].replace("something", "something2"));
like image 20
Eugene Avatar answered Oct 29 '25 06:10

Eugene



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!