英文:
How to Convert List<Map<String, Object>> to List<Map<String, String>>
问题
我正在从数据库查询中检索结果,格式为 List<Map<String, Object>>
,你能否提供建议,如何将其转换为 List<Map<String, String>>
。
英文:
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>>
.
答案1
得分: 3
迭代列表,依次转换其中的每个映射:
list.stream()
.map(map ->
map.entrySet().stream()
.collect(
Collectors.toMap(
Entry::getKey, e -> e.getValue().toString())))
.collect(Collectors.toList())
英文:
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())
答案2
得分: 1
一个简单的for-each循环遍历列表项及其映射条目即可完成:
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()); // 映射在这里进行
}
newList.add(newMap);
}
在我看来,这是最优解和最易读的解决方案。[tag:java-stream] 并不适用于与字典(映射)一起使用(尽管你总是从中获得一个集合)。
英文:
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 [tag:java-stream] is not suitable much for working with dictionaries (although you always get a collection from it).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论