Search code examples
javalambdaforeachjava-streamindexof

How to do substring in some elements of string list using lambda


Below is my list of String.

["sunday", "monday", "tuesday", "wednesday", "thurs", "fri", "satur"]

I want to do remove "day" from the elements, if it is ending with "day".

Expected Output in the list:

["sun", "mon", "tues", "wednes", "thurs", "fri", "satur"]

How to do this using Lambda?

I have tried the below code, but was unable to assign the value to the list:

daysList.stream().forEach(s -> {
    if (s.endsWith("day")) {
        s = s.substring(0, s.indexOf("day"));
    }
});

Solution

  • Most of the answers here make use of a Stream, but you should not be using a Stream at all:

    daysList.replaceAll(s -> s.replaceFirst("day$", ""));