Bala
Bala

Reputation: 823

Java 8 Iterate List inside an list and stream.map()

I am wondering if there is a single line option for this issue.

I have a bean like,

public class DataA {
    private String name;
    private String email;
    private List<String> accountNumberName;
}

Sample value in DataA is

name="user1",email="[email protected]",accountNumberName=["100", "101", "102"] etc..

I have a map of account number and Name Map<String, String> accountNumberNameMap Sample data in accountNumberNameMap is like,

{"100"="Account A", "101" = "Account B", "102" = "Account C"}

I want to convert DataA to name="user1",email="[email protected]",accountNumberName=["100 - Account A", "101 - Account B", "102 - Account C"]

I have a collection of DataA List<DataA> want to convert all my accountNumberName inside the 'List' to have account number - Account name using accountNumberNameMap.

I can do it by using couple of loops and then convert account Number to account number - account Name. Wondering if there is a easy way in Java8 stream to do it.

Upvotes: 1

Views: 2728

Answers (1)

Alexis C.
Alexis C.

Reputation: 93892

If you don't mind modifying the instances in the list directly, you can use forEach combined with replaceAll (I assumed I could access the accountNumberName for simplicity but you can easily change it also via a setter).

list.forEach(d -> d.accountNumberName.replaceAll(acc -> acc + " - " + accountNumberNameMap.getOrDefault(acc, "")));

If you don't want to modify the existing instances, it can be done this way (assuming a copy constructor exists):

list.replaceAll(d -> new DataA(d.name, d.email, d.accountNumberName.stream().map(name -> name + " - " + accountNumberNameMap.getOrDefault(name, "")).collect(toList())));

(and then if you don't want to modify the original list, just stream/collect over it instead of using replaceAll)

Upvotes: 2

Related Questions