如何将 List<Map<String, Object>> 转换为 List<Map<String, String>>。

huangapple go评论90阅读模式
英文:

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&lt;Map&lt;String, Object&gt;&gt; format, can you suggest, How to convert it to List&lt;Map&lt;String, String&gt;&gt;.

答案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 -&gt;
        map.entrySet().stream()
            .collect(
                Collectors.toMap(
                    Entry::getKey, e -&gt; 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&lt;Map&lt;String, Object&gt;&gt; list = ...
List&lt;Map&lt;String, String&gt;&gt; newList = new ArrayList&lt;&gt;();
	
for (Map&lt;String, Object&gt; map: list) {
	Map&lt;String, String&gt; newMap = new HashMap&lt;&gt;();
	for (Entry&lt;String, Object&gt; 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).

huangapple
  • 本文由 发表于 2020年5月5日 08:13:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/61603735.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定