集合去重方法,自备

 /**
     * 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;
    }

 

posted @ 2019-10-21 10:23  听着music睡  阅读(297)  评论(0编辑  收藏  举报