在编程中,我们经常需要将一种数据结构转换为另一种数据结构。这里的问题是将包含字符串对的列表转换为包含键值对映射的列表。
val list = List(("key1", "value1"), ("key2", "value2"), ("key3", "value3"))
// 转换为 List[Map[String, String]]
val listOfMaps = list.map { case (k, v) => Map(k -> v) }
// 结果: List(Map(key1 -> value1), Map(key2 -> value2), Map(key3 -> value3))
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Pair<String, String>> list = Arrays.asList(
new Pair<>("key1", "value1"),
new Pair<>("key2", "value2"),
new Pair<>("key3", "value3")
);
// 转换为 List<Map<String, String>>
List<Map<String, String>> listOfMaps = list.stream()
.map(pair -> {
Map<String, String> map = new HashMap<>();
map.put(pair.getKey(), pair.getValue());
return map;
})
.collect(Collectors.toList());
// 结果: [{key1=value1}, {key2=value2}, {key3=value3}]
}
}
// 简单的Pair类实现
class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() { return key; }
public V getValue() { return value; }
}
list_of_tuples = [("key1", "value1"), ("key2", "value2"), ("key3", "value3")]
# 转换为 List[Dict[str, str]]
list_of_dicts = [{k: v} for k, v in list_of_tuples]
# 结果: [{'key1': 'value1'}, {'key2': 'value2'}, {'key3': 'value3'}]
这种转换在以下场景中很有用:
对于大数据集,这种转换可能会消耗较多内存。如果不需要单独的Map结构,可以考虑其他更高效的数据组织方式。
没有搜到相关的文章