Skip to content
Advertisement

Generate a String from all values of a specific key from List in Java?

Suppose I have a list of Map such as: (Using json format just for demonstration)

JavaScript

Now I want all the “id” values in a single String object, separated by a separator. For example, the above map should give me:

JavaScript

Note: The order in which they are indexed in the list has to be maintained. I know I can do it like this:

JavaScript

But I want a more readable and simplified code, preferably using Java stream api.

Advertisement

Answer

You can use stream and join all the key id values which are not null

JavaScript

In case if you want to check if the value is String instance you can filter

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement