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.
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.
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With