I have the following code:
List<String> list= Arrays.asList("a","b","c");
list.stream()
.map(x->{
//if(isLast()) return "last";
return x;
})
.forEach(System.out::println);
I want to change the last item in the list with "last" so the program will return something like this
a
b
last
NOTE: I know I can do this very easy without streams, but I'm interested if this can be achieved with streams.
NOTE2: I provided a simple example, so I can easily understand the stream concept
How about this:
<T> Stream<T> replaceLast(List<T> items, T last) {
Stream<T> allExceptLast = items.stream().limit(items.size() - 1);
return Stream.concat(allExceptLast, Stream.of(last));
}
The method makes two separate streams, one containing all except the last item of the input list, and a second containing only the replacement final item. Then it returns the concatenation of those two streams.
Example invocation:
>>> List<String> items = Arrays.asList("one", "two", "three");
>>> replaceLast(items, "last").forEach(System.out::println);
one
two
last
Thinking about it, if using Stream.limit
is uncomfortable, Stream<T> allExceptLast = items.subList(0, items.size() - 1).stream();
is also possible.
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