Vamshi
Vamshi

Reputation: 55

Replace values in a List of Lists from a Map in Java 8

I have a Map that has all these values :

Map :

B Bonus
C Cash
D Draft

And I have a list of Lists : Account :

Number, Type, Name

AccountsList

Account 0 : 123, B, Sam

Account 1 : 124, C, Harry

I have to update the values in AccountList based on Keyvalue pair in Map.

I have the below code:

for (Account acc: AccountList) {
        acc.setAccountType(map.get(acc.getAccountType()));
    }

How do I write the above code using Java 8 streams

Upvotes: 1

Views: 1668

Answers (3)

Michael Mesfin
Michael Mesfin

Reputation: 556

if you want to return a new List without modifying the existing one

 List<AccountList> updatedAccountList = accountLists.stream().map(a -> {
            AccountList newAccountList = new AccountList();
            newAccountList.setType(map.get(a.getType()));
            return newAccountList;
        }).collect(Collectors.toList());

Upvotes: 0

user1729
user1729

Reputation: 95

You can try with forEach:

AccountList.stream().forEach(acc -> acc.setAccountType(map.get(acc.getAccountType())))

Upvotes: 2

Morteza Jalambadani
Morteza Jalambadani

Reputation: 2445

you can do this by parallelStream:

AccountList = 
    AccountList.
    parallelStream().
    peek(
        acc -> acc.setAccountType(
                   map.get(acc.getAccountType())
               )
    ).collect(
        Collectors.toList()
    );

Upvotes: 1

Related Questions