List<Map>中根据某个属性去重,不重复的值则覆盖null

 /**
     *     根据map中的某个key 去除List中重复的map,如果值不为null,则覆盖空值
     * @author  shijing
     * @param list
     * @param mapKey
     * @return
     */
    public  List<Map<String, String>> removeRepeatMapByKey(List<Map<String, String>> 
           list){
        if (list.size()<=0) return null;
      //用于保存合并后的List数据
        List<Map<String,String>> listCopy = new ArrayList<Map<String,String>>();

        //遍历原始List
        for (Map<String, String> userInfo : list) {
            String time = (String) userInfo.get("time");
            String left = null;
            String middle =null;
            String right = null;
            if(userInfo.get("left")!=null) {
                left = (String) userInfo.get("left");
            }
            if(userInfo.get("middle")!=null) {
                middle = (String) userInfo.get("middle");
            }
            if(userInfo.get("right")!=null) {
                right = (String) userInfo.get("right");
            }
            int j = 0;
            //遍历合并后的List
            for (Map<String, String> userInfoCopy : listCopy) {
                String timeCopy = (String) userInfoCopy.get("time");
                //根据Map的Key判断,如果已经存在,则把ItemName加入进去并且用逗号隔开
                if(time.equals(timeCopy)) {
                    if(left!=null) {
                        userInfoCopy.put("left", left);
                    }
                    if(middle!=null) {
                        userInfoCopy.put("middle", middle);
                    }
                    if(right!=null) {
                        userInfoCopy.put("right", right);
                    }
                    j++;
                }
            }
            //如果不存在,则把本条数据直接插入
            if(j == 0) {
                listCopy.add(userInfo);
            }
        }
        return listCopy;
    }

 

posted @ 2021-01-21 11:21  憨憨青年  阅读(383)  评论(0编辑  收藏  举报
// 侧边栏目录 // https://blog-static.cnblogs.com/files/douzujun/marvin.nav.my1502.css