Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
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

like image 986
Doua Beri Avatar asked Nov 29 '22 23:11

Doua Beri


1 Answers

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.

like image 181
Sam Avatar answered Dec 04 '22 11:12

Sam