我有两个列表:
1列表包含DB中的所有客户,第二个列表仅包含DB中的部分客户:
List<Customers> allCustomers = findAll();
List<Customers> inUseCustomers = findAllCustomersInUse();
我有另一个对象调用:CustomerDto
public class CustomerDto {
private Customer _customer;
private boolean _inUse;
public CustomerDto(Customer customer, boolean inUse) {
this._customer = customer;
this._inUse = inUse;
}
}
我想创建一个新的CustomerDto列表,其中包含所有客户,但对于那些正在使用的客户,他们的字段"inUse"为真,其余为假。
我如何以一种干净的方式使用stream ?
伙计,我相信你可以做这样的事情,如果我知道你想做什么,你的代码可能是如何工作的:
List<CustomerDto> customerDtoList = new ArrayList<>();
for(Customer customer : allCustomers) {
CustomerDto customerDto = new CustomerDto(customer, customer.isInUse());
customerDtoList.add(customerDto);
}
这里,您只是实例化了一个新的CustomerDto对象,其中包含allCustomers列表中的客户,以及它的变量inuse的值。然后,这个对象被添加到List对象中。
我不知道我写的是否正确,也许你也可以做一些重构,但正如上面另一个人说的,如果我们知道你已经尝试了什么,会更容易。我希望我的回答至少能让你知道该怎么做。