Reputation: 337
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"));
}
});
Upvotes: 8
Views: 20943
Reputation: 13
Sub String with decimal points sorting .
String arr[]= {"2.4","4.2","3.1","5.7","3.0","2.01","7.06","6.003"};
List newList =Arrays.asList(arr); newList.stream().map(n -> n.substring(n.indexOf('.')) ).collect(Collectors.toList()).stream().sorted().forEach(n -> System.out.println(n));;
Upvotes: 1
Reputation: 2920
Iterating over the stream using forEach
won't work; you need to map each of the elements you modified to a new stream using map
. Then you can collect the results back to your list.
daysList = daysList.stream()
.map(s -> s.endsWith("day") ? s.substring(0, s.length()-3) : s)
.collect(Collectors.toList());
Upvotes: 8
Reputation: 44318
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$", ""));
Upvotes: 16
Reputation: 716
List<String> daysList = Arrays.asList("sunday", "monday",
"tuesday", "wednesday",
"fri", "satur"
);
List<String> res = daysList.stream()
.map(s -> s.replace("day",""))
.collect(Collectors.toList());
Upvotes: 1