簡體   English   中英

如何比較兩個列表並使用新對象創建新列表

[英]How can i compare two lists and create new list with with new object

我有 2 個列表:

1 列表包含數據庫中的所有客戶,第二個列表僅包含數據庫中的部分客戶:

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”將為真,其余為假。

我怎樣才能以一種干凈的方式使用流來做到這一點?

伙計,我相信你可以做這樣的事情,如果我知道你想要做什么以及你的代碼如何工作:

List<CustomerDto> customerDtoList = new ArrayList<>();

for(Customer customer : allCustomers) {
    CustomerDto customerDto = new CustomerDto(customer, customer.isInUse());
    customerDtoList.add(customerDto);
}

在這里,您只是使用 allCustomers 列表中的客戶及其變量“inUse”的值來實例化一個新的 CustomerDto 對象。 然后,這個對象被添加到 List 對象中。

我不知道我寫的是否全部正確,也許您也可以進行一些重構,但正如上面另一個人所說,如果我們知道您已經嘗試過的內容會更容易。 我希望我的回答至少能讓你知道該怎么做:v。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM