1

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.

Alexis C.
94.2k22 gold badges173 silver badges179 bronze badges
asked Aug 23, 2017 at 21:08
4
  • What do you want to do when the map doesn't contain the account number? Commented Aug 23, 2017 at 21:45
  • I think accountNumberNameMap.getOrDefault(acc, "") should handle it. Commented Aug 23, 2017 at 21:54
  • the question wasn't how to code it, but what the behavior should be. So, your answer is to use a blank string, right, like a left-join works? Commented Aug 23, 2017 at 21:59
  • Yes.. I need an empty string. :-) Commented Aug 23, 2017 at 22:08

1 Answer 1

2

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)

answered Aug 23, 2017 at 21:23
1
  • I wanted to update the instances in the list directly.. Thanks for quick reply. Commented Aug 23, 2017 at 21:40

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.