Doua Beri Doua Beri - 8 months ago 88
Java Question

java 8 stream : Use map to change last element in a List

I have the following code:

List<String> list= Arrays.asList("a","b","c");
// if(isLast()) return "last";
return x;

I want to change the last item in the list with "last" so the program will return something like this


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

Sam Sam

How about this:

<T> Stream<T> replaceLast(List<T> items, T last) {
    Stream<T> allExceptLast = - 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);

Thinking about it, if using Stream.limit is uncomfortable, Stream<T> allExceptLast = items.subList(0, items.size() - 1).stream(); is probably preferable.