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>>.
2 Answers
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())
1 Comment
javaHolic
Thanks a ton, you save my day.
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 java-stream is not suitable much for working with dictionaries (although you always get a collection from it).
4 Comments
javaHolic
Awesome, your solution worked flawless - you save my day.
Nikolas
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.
Andy Turner
@Nikolas what do you mean "The java-stream is not suitable much for working with dictionaries"?
Andy Turner
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.