JAVA 函数如何对多个JSONArray取交集,取并集

来源:互联网 发布:sql基础教程 pdf 编辑:程序博客网 时间:2024/06/10 15:40
/**   * 根据JSONArray中JSONObject的id不同取交集   * @return   */    public static JSONArray intersectResult(JSONArray... arrays){        JSONArray ret = new JSONArray();        if(arrays==null||arrays.length==0)            return ret;        Set<String> first_ids=new HashSet<String>();        Map<String,JSONObject> objs=new HashMap<String, JSONObject>();        JSONArray first=arrays[0];        for(int i=0;i<first.length();i++){            JSONObject o =first.getJSONObject(i);            String id=o.getString("id");            first_ids.add(id);            objs.put(id, o);        }        for(int i=1;i<arrays.length;i++){            JSONArray this_array=arrays[i];            Set<String> this_ids=new HashSet<String>();            for(int j=0;j<this_array.length();j++){                this_ids.add(this_array.getJSONObject(j).getString("id"));            }            first_ids.retainAll(this_ids);        }        for(String id : first_ids){            ret.put(objs.get(id));        }        return ret;    }  /**   * 根据JSONArray中JSONObject的id不同取并集   * @param arrays   * @return   */  public static JSONArray joinJSONArray(JSONArray... arrays){      JSONArray ret=new JSONArray();      Set<String> ids=new HashSet<String>();      for(JSONArray array : arrays){          if(array==null)              continue;          for(int i=0;i<array.length();i++){              JSONObject obj=array.getJSONObject(i);              if(ids.contains(obj.get("id")))                  continue;              ret.put(obj);              ids.add(obj.getString("id"));          }      }      return ret;  }
原创粉丝点击