Er KK Chopra
Er KK Chopra

Reputation: 1850

How to get a List from string from List of Map with Java 8 Stream?

I have list of hash maps and I am looking for list of UserId.

Data like:

[
 {UserId=10033, name=Siegmund},
 {UserId=10034, name=Sied},
 {UserId=10035, name=mund}
]

I am trying like:

List<HashMap<String, Object>> result = 
    (List<HashMap<String, Object>>) resultMap.get("resultList");
result.forEach(mapObj -> {
    System.out.println(mapObj.get("UserId"));
});

But looking for some better solution for this. Thanks

Upvotes: 1

Views: 332

Answers (2)

Karthik HG
Karthik HG

Reputation: 17

From your data , you can have Map , why list of Maps. You can try something like below

Map<String,String> listMap = new HashMap<>();
        listMap.put("10033","Siegmund");
        listMap.put("10034","Sied");
        listMap.put("10035","mund");

        List<String> userIDList = listMap.entrySet().stream().map(Map.Entry::getKey).collect(Collectors.toList());

        userIDList.stream().forEach(System.out::println);

or if you really need to parse through list of Maps then you can do as below

List<String> userIDList = listOfMaps.stream().map(Map::entrySet).flatMap(Collection::stream).map(Map.Entry::getKey).collect(Collectors.toList());

        userIDList.stream().forEach(System.out::println);

Upvotes: 0

ernest_k
ernest_k

Reputation: 45309

You can pull all name values into a single list using something like this:

List<HashMap<String, Object>> list = ...;
List<Integer> userIds = list.stream()
                        .map(map -> (Integer) map.get("UserId"))
                        .collect(Collectors.toList());

Upvotes: 1

Related Questions