Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include elements from unmodified list in modified list with Java Streams?

I am trying to do a map operation on a List<Integer>:

list.stream().map(i -> i - 2).collect(Collectors.toList());

Instead of performing the operation on the last element of the list, I would like it to just be passed through. ...Collectors.toList()).add(i) doesn't work, of course, because i is out of scope.

For example, the input list [1, 2, 3, 4] should output [-1, 0, 1, 4]

like image 562
ack Avatar asked Feb 19 '26 23:02

ack


2 Answers

List<Integer> result = 
    list.subList(0, list.size() - 1)
        .stream().map(i -> i - 2)
        .collect(Collectors.toCollection(ArrayList::new));
result.add(list.get(list.size() - 1));
like image 72
JB Nizet Avatar answered Feb 21 '26 11:02

JB Nizet


You could stream the original list and limit the stream to exclude the last element, do the mapping and collect to a new ArrayList, then add the last element of the original list to the last position of the new, mutable list:

int size = list.size();

List<Integer> result = list.stream()
    .limit(size - 1)
    .map(i -> i - 2)
    .collect(Collectors.toCollection(() -> new ArrayList(size)));

result.add(list.get(size - 1));

Another way would be to do the mapping and collect all the elements of the original list into the new list and then simply set the last element of the original list in the last position of the new list, overwriting the previous element:

int size = list.size();

List<Integer> result = list.stream()
    .map(i -> i - 2)
    .collect(Collectors.toCollection(() -> new ArrayList(size)));

result.set(size - 1, list.get(size - 1));
like image 45
fps Avatar answered Feb 21 '26 13:02

fps



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!