第二题解答答案:
1的代码还可以更简单一点
1.这个时间复杂度为2N
public List<Map<String, Object>> mergeList3(List<Map<String, Object>> list1, List<Map<String, Object>> list2, String fieldName) { Map<Object, Map<String, Object>> temp = new HashMap<>(); list1.forEach(i -> processItem(i, temp, fieldName)); list2.forEach(i -> processItem(i, temp, fieldName)); List<Map<String, Object>> resMap = new ArrayList<>(temp.values()); return resMap; } public void processItem(Map<String, Object> map, Map<Object, Map<String, Object>> resultMap, String fieldName) { if(map.get(fieldName) != null) { Map<String, Object> objMap = resultMap.get(map.get(fieldName)); if(objMap != null) { objMap.putAll(map); } else { resultMap.put(map.get(fieldName), map); } } }
2.这个时间复杂度为N^2
public List<Map<String, Object>> mergeList(List<Map<String, Object>> list1, List<Map<String, Object>> list2, String fieldName) { for (int i=0; i<list1.size(); i++) { for (int j=0; j<list2.size(); j++) { if(list1.get(i).get(fieldName).equals(list2.get(j).get(fieldName))) { list1.get(i).putAll(list2.get(j)); } } } return list1; }