如何使用Java Streams在修改后的列表中包含未修改列表中的元素? [英] How to include elements from unmodified list in modified list with Java Streams?

查看:119
本文介绍了如何使用Java Streams在修改后的列表中包含未修改列表中的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在列表<整数> 上执行 map 操作:

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

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

我希望它只是通过而不是对列表的最后一个元素执行操作通过。 ... Collectors.toList())。add(i)当然不起作用,因为 i 超出范围。

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.

例如,输入列表 [1,2,3,4] 应输出 [ - 1,0,1,4]

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

推荐答案

您可以流式传输原始列表限制流以排除最后一个元素,执行映射并收集到新的 ArrayList ,然后将原始列表的最后一个元素添加到new的最后一个位置,可变list:

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

这篇关于如何使用Java Streams在修改后的列表中包含未修改列表中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆