首页 > 代码库 > List<Map<String, String>> 转 Map<String, List<String>>

List<Map<String, String>> 转 Map<String, List<String>>

将List转成Map结构,以下为没有水平的写法!

好久之前写的土方法转换,不知道有没有优秀的解法,还希望大家提供!

Map<String, String> map1 = new HashMap<String, String>();
map1.put("a", "1");
map1.put("b", "3");
map1.put("c", "5");

Map<String, String> map2 = new HashMap<String, String>();
map2.put("a", "2");
map2.put("b", "4");
map2.put("c", "6");

List<Map<String, String>> lm = new ArrayList<Map<String, String>>();
lm.add(map1);
lm.add(map2);

Map<String, List<String>> ml = new HashMap<String, List<String>>();
for (int i = 0; i < lm.size(); i++) {
	Map<String, String> m = lm.get(i);
	Iterator<Map.Entry<String, String>> it = m.entrySet().iterator();
	while (it.hasNext()) {
		Map.Entry<String, String> entry = it.next();
		List<String> al = ml.get(entry.getKey());
		if (al == null) {
			al = new ArrayList<String>();
		}
		al.add(entry.getValue());
		ml.put(entry.getKey(), al);
	}
}

System.out.println(ml);// {b=[3, 4], c=[5, 6], a=[1, 2]}