简体   繁体   中英

How to set specific filtered item in a list with stream in Java?

I am checking if an object is null and then I am creating new item if it is null and I want to set it into list but my method is not working. Here is the code:

Optional<Account> cryptoAccount = accountList.stream()
                .filter(account -> account.getAccountCurrencyType().equalsIgnoreCase(requestDto.getCurrency()))
                .findFirst();

if (cryptoAccount.isEmpty()) {
            cryptoAccount = Optional.of(createAccount(requestDto));

//here I want to set the specific account in the list but I could not achieve the chain.

            accountList.stream()
                    .filter(account -> account.getAccountCurrencyType().equalsIgnoreCase(requestDto.getCurrency()))
                    .map(Account::cryptoAccount);
        }

How can I write the correct chain?

As far as I understand your question, you do not filter any null objects. You are finding all accounts which have the same accountCurrencyType as requestDto.getCurrency(). So if there is no account with this currency what you want to do? Create a new account and add it to your accountList?

Why not just?

if (cryptoAccount.isEmpty(){
  accountList.add(createAccount(requestDto));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM