java - 迭代Java8时更新列表中的元素

标签 java list arraylist collections java-8

我有 Customer 对象的 List。我想迭代列表并将订单增加一。

我尝试了每个,但在这里我必须创建新列表并在其中添加值。

class Customer{
    long id;
    int orders;
    //getters setters constructor
}

List<Customer> empList=Arrays.asList(new Customer(1,10),new Customer(2,,20));

List<Customer> empList1=new ArrayList<>();
empList.forEach(e->{
    e.orders++; //updating orders
    empList1.add(e);
}); 

有更好的方法吗?我尝试使用流,但它只是映射订单

empList.stream().map(e->{e.orders++;}).collect(Collectors.toList());

最佳答案

您可以使用查看

empList.stream().peek(e->{e.orders++;}).collect(Collectors.toList());

正如“Vasanth Senthamarai Kannan”正确指出的那样,您不需要第二个列表,因为您没有修改列表的结构,

empList.forEach(e->e.orders++);

关于java - 迭代Java8时更新列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55793552/

相关文章:

java - Apache POI 3.10 最终 XWPFDocument.setParagraph()

java - 在 Spring 中实例化 Util 类

java - 查找字符串和字符串前缀之间最长后缀长度的算法

list - 是否有相当于 Ruby 的 #map 的 Groovy?

java - 创建变量中定义的类的 ArrayList

java - ArrayList 声明和处理

java - 验证枚举值仅出现一次

java - spring 下载文件 Controller 中重定向的错误处理

Java,在对象列表中搜索?

python - 对 python 列表的子集进行排序,使其具有与其他列表中相同的相对顺序