前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >集合去重方法,自备

集合去重方法,自备

作者头像
听着music睡
发布2019-10-23 16:12:28
3790
发布2019-10-23 16:12:28
举报
文章被收录于专栏:Android干货
代码语言:javascript
复制
 /**
     * xqx 去除未知object集合的重复数据
     * @param oldList  老数据集合
     * @param newList  新数据集合
     * @param key       唯一标识
     * @param <T>
     * @return
     */
    public static <T>ArrayList removeRepeatElement(List<T> oldList , List<T> newList , String key){
        ArrayList<T> resultList = new ArrayList<>();
        ArrayList<String> keys = new ArrayList<>();// 老数据中存在的唯一标识
        // 获取到原来数据中的所有位置标识
        for (int i = 0; i < oldList.size(); i++) {
            try {
                JSONObject oldDataJson = new JSONObject(new Gson().toJson(oldList.get(i), Object.class));
                String currentKey = String.valueOf(oldDataJson.get(key));
                if (!keys.contains(currentKey)){
                    keys.add(currentKey);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        // 遍历新的数据,如果有相同的唯一标识,则remove
        for (int i = newList.size()-1; i >=0 ; i--) {
            try {
                JSONObject newDataJson = new JSONObject(new Gson().toJson(newList.get(i), Object.class));
                String currentKey = String.valueOf(newDataJson.get(key));
                if (keys.contains(currentKey)){
                    // 重复key
                    newList.remove(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        // 避免返回null
        if (newList!=null){
            resultList.addAll(newList);
        }
        return resultList;
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-10-21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档