繁体   English   中英

使用java计算json文件上的重复数据

[英]count dupplicated data on json file using java

我正在尝试计算 json 文件中的所有重复数据,但我没有得到正确的数据计数,我想在将数据添加到列表之前对其进行排列,但可以排列 json 数据吗? 我对输出的看法:

component : pensil : 5 
               pen : 1

这是我的代码。 一些提示家伙谢谢。

public Main1(){
    BufferedReader br = null;
    JSONParser parser = new JSONParser();
    String inputline,aa;
    List<String> list = new ArrayList<String>();
    try {
            br = new BufferedReader(new FileReader("/Users/lyod/Documents/sample.json"));
        try {
            String id = null,component = null,title = null,lat = null,
            lng = null, cost = null, status = null;
            while ((inputline = br.readLine()) != null) {
                JSONArray a = (JSONArray) parser.parse(inputline);
                for (Object o : a) {
                    JSONObject sample = (JSONObject) o;
                    id = (String) sample.get("id");
                    component = (String) sample.get("component");
                    list.add(component);
                    aa =(component+" " + Collections.frequency(list, component));
                }
                System.out.println(aa);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }   
}

如果你打开使用第三方库,你可以使用一个HashBagEclipse的集合,一个HashBag从阿帕奇百科全书集合或HashMultiset番石榴。

您可以像任何其他收藏一样将您的物品添加到Bag / Multiset ,并且它们会在内部为您跟踪计数。

注意:我是 Eclipse Collections 的提交者。

我会这样:

  1. 创建HashMap<String, Integer> ,让 key 为组件, value 为出现次数。
  2. 我们将向您JSON文件用while为你做。 对于每个组件检查哈希映射中的存在 - 如果存在,则将值增加 1,如果不存在,则将新值 1 放在组件的键下。
  3. 循环打印所有键(组件)和值(重复数)。

你完成了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM