List<Map<String, Object>> 去出重复
作者:互联网
List<Map<String, Object>> 去出重复
public static void main(String[] args) {
String [] array= {"name","age"};
List<Map<String, Object>> oldList = getTestData();
getListMap(oldList,"name",array);
getListMap(oldList,"name");
System.out.println(getListMap(oldList,"name",array));
}
public static List<Map<String, Object>> getTestData() {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "A");
map.put("age", "0");
map.put("age1", "0");
Map<String, Object> map1 = new HashMap<String, Object>();
map1.put("name", "B");
map1.put("age", "1");
map.put("age1", "0");
Map<String, Object> map2 = new HashMap<String, Object>();
map2.put("name", "A");
map2.put("age", "1");
map.put("age1", "1");
list.add(map);
list.add(map1);
list.add(map2);
return list;
}
1.去出重复的key
/**
* List<Map<String, Object>> 去出重复的key
* @param str Map<String, Object> 中对比的key
* @return
*/
public static List<Map<String, Object>> getListMap(List<Map<String, Object>> oldList,String str) {
List<Map<String, Object>> newList = new ArrayList<Map<String, Object>>();
for (int i = 0; i < oldList.size(); i++) {
Map<String, Object> oldMap = oldList.get(i);
if (newList.size() > 0) {
boolean isContain = false;
for (int j = 0; j < newList.size(); j++) {
Map<String, Object> newMap = newList.get(j);
if (newMap.get(str).equals(oldMap.get(str))) {
for (String key : oldMap.keySet()) {
newMap.put(key, oldMap.get(key));
}
isContain = true;
break;
}
}
if (!isContain) {
newList.add(oldMap);
}
} else {
newList.add(oldMap);
}
}
return newList;
}
2.去出重复的key,保留这定的key
/**
* List<Map<String, Object>> 去出重复的key,保留这定的key
* @param str Map<String, Object> 中对比的key
* @param array 需要保留的key
* @return
*/
public static List<Map<String, Object>> getListMap(List<Map<String, Object>> oldList,String str,String [] array) {
List<Map<String, Object>> newList = new ArrayList<Map<String, Object>>();
for (int i = 0; i < oldList.size(); i++) {
Map<String, Object> oldMap = oldList.get(i);
Map<String, Object> oldMap1 = new HashMap<String, Object>();
for (String arr : array) {
oldMap1.put(arr, oldMap.get(arr));
}
if (newList.size() > 0) {
boolean isContain = false;
for (int j = 0; j < newList.size(); j++) {
Map<String, Object> newMap = newList.get(j);
if (newMap.get(str).equals(oldMap.get(str))) {
isContain = true;
break;
}
}
if (!isContain) {
newList.add(oldMap1);
}
} else {
newList.add(oldMap1);
}
}
return newList;
}
标签:Map,get,重复,newList,List,key,put 来源: https://www.cnblogs.com/yuangyuan/p/16449547.html