将HashMap的ArrayList映射到另一个HashMap的ArrayList可以通过以下步骤实现:
下面是一个示例代码:
import java.util.ArrayList;
import java.util.HashMap;
public class HashMapArrayListMapping {
public static ArrayList<HashMap<String, String>> mapArrayList(ArrayList<HashMap<String, String>> originalList) {
ArrayList<HashMap<String, String>> mappedList = new ArrayList<>();
for (HashMap<String, String> map : originalList) {
HashMap<String, String> newMap = new HashMap<>();
for (String key : map.keySet()) {
String value = map.get(key);
// 检查新的HashMap的ArrayList中是否已存在相同的键
boolean keyExists = false;
for (HashMap<String, String> existingMap : mappedList) {
if (existingMap.containsKey(key)) {
existingMap.put(key, existingMap.get(key) + ", " + value);
keyExists = true;
break;
}
}
// 如果不存在相同的键,则创建新的键值对
if (!keyExists) {
newMap.put(key, value);
}
}
mappedList.add(newMap);
}
return mappedList;
}
public static void main(String[] args) {
// 示例用法
ArrayList<HashMap<String, String>> originalList = new ArrayList<>();
HashMap<String, String> map1 = new HashMap<>();
map1.put("key1", "value1");
map1.put("key2", "value2");
originalList.add(map1);
HashMap<String, String> map2 = new HashMap<>();
map2.put("key2", "value3");
map2.put("key3", "value4");
originalList.add(map2);
ArrayList<HashMap<String, String>> mappedList = mapArrayList(originalList);
// 输出映射结果
for (HashMap<String, String> map : mappedList) {
for (String key : map.keySet()) {
System.out.println(key + ": " + map.get(key));
}
}
}
}
这是一个简单的示例,它将原始的HashMap的ArrayList映射到另一个HashMap的ArrayList,并将具有相同键的值合并到同一个键的值列表中。你可以根据实际需求进行修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云