我有 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/