package com.aisino.behavior.util;
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @ClassName ccc
* @Description TODO
* @Author zhanggesheng
* @Date 2020/10/15 16:22
* @Version 1.0
*/
public class ccc {
public static void main(String[] args) {
String aa = " [{ \"userId\": \"8816\", \"userName\": \"hbdc2\", \"realName\": \"湖北测试用户\", \"deptId\": \"9936\", \"userType\": \"\" }, { \"userId\": \"8048\", \"userName\": \"cc\", \"realName\": \"熊\", \"deptId\": \"9936\", \"userType\": \"\" }, { \"userId\": \"1232\", \"userName\": \"xlp2\", \"realName\": \"熊\", \"deptId\": \"9936\", \"userType\": \"\" }]";
String bb = " [{ \"userId\": \"8816\", \"userName\": \"hbdc2\", \"realName\": \"湖北测试用户\", \"deptId\": \"9936\", \"userType\": \"区域财务负责人\" }, { \"userId\": \"8048\", \"userName\": \"cc\", \"realName\": \"熊\", \"deptId\": \"9936\", \"userType\": \"区域财税人员\" }, { \"userId\": \"1232\", \"userName\": \"xlp2\", \"realName\": \"熊\", \"deptId\": \"9936\", \"userType\": \"区域财税人员\" }]";
List<Object> recodeList = new ArrayList<>();
List<Map> resultList = new ArrayList<>();
recodeList = JSONObject.parseArray(aa,Object.class);
resultList = JSONObject.parseArray(bb,Map.class);
getList(recodeList,resultList);
}
public static List<?> getList(List<?> recode, List<Map> result) {
// List<Object> manageList = new ArrayList<>();
// for (int i = 0; i < recode.size(); i++) {
// Object obj = recode.get(i);
// JSONObject jsonObject = (JSONObject) JSONObject.toJSON(obj);
// String deptId = jsonObject.get("deptId").toString();
//
// for (int j = 0; j < result.size(); j++) {
// String deptId2 = (String) result.get(j).get("deptId");
// if (deptId.equals(deptId2)) {
// jsonObject.put("userType", result.get(j).get("userType"));
// }
// manageList.add(jsonObject);
// }
// } return manageList;
// *****以下为优化后代码******
List<String> resultDeptIdList = result.stream().map(e -> e.get("deptId").toString()).collect(Collectors.toList());
List newRecord =recode.stream().map(e -> {
JSONObject newObj = (JSONObject) JSONObject.toJSON(e);
if (resultDeptIdList.contains(newObj.get("deptId").toString())) {
newObj.put("userType", result.stream().filter(x -> newObj.get("deptId").toString().equals(x.get("deptId").toString())).findFirst().get().get("userType"));
}
; return newObj;}).collect(Collectors.toList());
return newRecord;
}
}
今日遇到同事问到一个问题,对于泛型的接口,统一处理后泛型返回。我让他转jsonObject后处理,然后返回List<Object>;过了一会我看了代码就觉得可以优化一下。然后就用java8的处理了一下。逻辑为两个数组,根据匹配id,将匹配上的那个map中的值赋值给泛型对象中。