1

I am retrieving results from DB Query as List<Map<String, Object>> format, can you suggest, How to convert it to List<Map<String, String>>.

0

2 Answers 2

3

Iterate the list, transforming each of the maps in turn:

list.stream()
    .map(map ->
        map.entrySet().stream()
            .collect(
                Collectors.toMap(
                    Entry::getKey, e -> e.getValue().toString())))
    .collect(Collectors.toList())
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a ton, you save my day.
1

A simple for-each iteration over the list items and its map entries does the trick:

List<Map<String, Object>> list = ...
List<Map<String, String>> newList = new ArrayList<>();

for (Map<String, Object> map: list) {
    Map<String, String> newMap = new HashMap<>();
    for (Entry<String, Object> entry: map.entrySet()) {
        newMap.put(entry.getKey(), entry.getValue().toString()); // mapping happens here
    }
    newList.add(newMap);
}

In my opinion, this is the optimal solution and the most readable solution. The is not suitable much for working with dictionaries (although you always get a collection from it).

4 Comments

Awesome, your solution worked flawless - you save my day.
Welcome. As long as you are new here, let me suggest you consider marking the best answer as accepted (green tick) (up to your choice) and eventually upvote (this action is optional, it's like saying "thank you, it helps"). The acceptance is an indicator that this issue has been resolved for the future incomers.
@Nikolas what do you mean "The java-stream is not suitable much for working with dictionaries"?
Aside: map.forEach((k, v) -> newMap.put(k, v.toString())); is a neater way to do the inner-most loop: having to deal with map entries always feels gross.

Your Answer

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.