如何使用Stream API更新Java 8中List中的每个元素 [英] How to update each element in a List in Java 8 using Stream API

查看:2421
本文介绍了如何使用Stream API更新Java 8中List中的每个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个List定义如下:

I have a List defined as follows:

List<Integer> list1 = new ArrayList<>();
list1.add(1); 
list1.add(2);

如何将List的每个元素递增一个(即以List <$ c结尾) $ c> [2,3] )使用Java 8的Stream API而不创建新的List?

How can I increment each element of the List by one (i.e. end up with a List [2,3]) using Java 8's Stream API without creating new List?

推荐答案

当您从列表创建时,不允许修改源列出 https://docs.oracle.com/javase/8/docs/api包文档中的/java/util/stream/package-summary.html#NonInterferencerel =noreferrer>Non-interference部分。不遵守此约束可能会导致 ConcurrentModificationException ,或者更糟糕的是,导致数据结构损坏而不会出现异常。

When you create a Stream from the List, you are not allowed to modify the source List from the Stream as specified in the "Non-interference" section of the package documentation. Not obeying this constraint can result in a ConcurrentModificationException or, even worse, a corrupted data structure without getting an exception.

使用Java Stream直接操作列表的唯一解决方案是创建一个不在列表本身上迭代的Stream,即迭代索引的流,如

The only solution to directly manipulate the list using a Java Stream, is to create a Stream not iterating over the list itself, i.e. a stream iterating over the indices like

IntStream.range(0, list1.size()).forEach(ix -> list1.set(ix, list1.get(ix)+1));

,如 Eran的答案

但是没有必要使用 Stream 这里。目标可以简单实现

But it’s not necessary to use a Stream here. The goal can be achieved as simple as

list1.replaceAll(i -> i + 1);

这是一个新的列表方法在Java 8中引入,也允许顺利使用lambda表达式。除此之外,还有一个众所周知的 Iterable.forEach ,好的 Collection.removeIf 和就地 List.sort 方法,用于命名其他不涉及Stream API的新Collection操作。此外, 地图 界面有几个值得了解的新方法。

This is a new List method introduced in Java 8, also allowing to smoothly use a lambda expression. Besides that, there are also the probably well-known Iterable.forEach, the nice Collection.removeIf, and the in-place List.sort method, to name other new Collection operations not involving the Stream API. Also, the Map interface got several new methods worth knowing.

另请参阅利用Java SE 8中的Lambda表达式和流的新增和增强的API 来自官方文档。

See also "New and Enhanced APIs That Take Advantage of Lambda Expressions and Streams in Java SE 8" from the official documentation.

这篇关于如何使用Stream API更新Java 8中List中的每个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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