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)

List<Map> myList = [
    {
        "id": 12,
        "name": "Harie"
    },
    {
        "id": "Forty",
        "location": "Earth"
    },
    {
        "name": "Potah"
    },
    {
        "id": "0"
    }
]

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

"12#Forty#0"

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

        StringBuilder result = new StringBuilder();
        for (Map map : myList) {
            if (map.get("id") instanceof String) {
                if(result.length()>0){
                    result.append('#');
                }
                result.append(map.get("id"));
            }
        }
        //Use result.toString() for output

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

String keyString = myList.stream()
           .map(map->map.get("id"))
           .filter(Objects::nonNull)
           .map(Object::toString)
           .collect(Collectors.joining("#"));

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

filter(val-> val!=null && val instance String)
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement