//不建议使用Map保存这些,使用实体bean更好
package
com.rxlamo.zhidao;
import
java.util.*;
public
class
Main {
public
static
void
main(String[] args) {
List<Map<String, Object>> list =
new
ArrayList<>(
4
);
/*
* map1:{ID:4,身高:170,体重:60}
map2:{ID:4,年龄:20,性别:男}
map3:{ID:5,身高:160,体重:50}
map4:{ID:5,年龄:19,性别:女}
*/
Map<String, Object> map1 =
new
HashMap<>();
map1.put(
"ID"
,
4
);
map1.put(
"身高"
,
170
);
map1.put(
"体重"
,
60
);
list.add(map1);
Map<String, Object> map2 =
new
HashMap<>();
map2.put(
"ID"
,
4
);
map2.put(
"年龄"
,
20
);
map2.put(
"性别"
,
'男'
);
list.add(map2);
Map<String, Object> map3 =
new
HashMap<>();
map3.put(
"ID"
,
5
);
map3.put(
"身高"
,
160
);
map3.put(
"体重"
,
50
);
list.add(map3);
Map<String, Object> map4 =
new
HashMap<>();
map4.put(
"ID"
,
5
);
map4.put(
"年龄"
,
19
);
map4.put(
"性别"
,
'女'
);
list.add(map4);
merge(list);
for
(
int
i =
0
; i < list.size(); i++) {
Map<String, Object> map = list.get(i);
System.out.println(map);
}
}
private
static
void
merge(List<Map<String, Object>> list) {
for
(
int
i =
0
; i < list.size(); i++) {
Map<String, Object> map = list.get(i);
// 从当前项的下一项开始检查
for
(
int
j = i +
1
; j < list.size(); j++) {
Map<String, Object> childMap = list.get(j);
// ID 相等
if
(map.get(
"ID"
).equals(childMap.get(
"ID"
))) {
// 合并,此处需要先 remove
list.remove(childMap);
map.putAll(childMap);
}
}
}
}
}