使用 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();
}
}
我会这样:
- 创建
HashMap<String, Integer>
,键为组件,值为出现次数。
- 像您一样使用
while
浏览 json 文件。对于每个组件,检查哈希映射中是否存在 - 如果存在,则将值增加 1,如果不存在,则将新值 1 放在组件的键下。
- 循环打印所有键(组件)和值(重复计数)。
大功告成。
如果您愿意使用第三方库,可以使用来自 Guava 的 HashBag from Eclipse Collections, a HashBag from Apache Commons Collections or a HashMultiset。
您可以像任何其他集合一样将您的项目添加到 Bag
/Multiset
,他们会在内部为您跟踪计数。
注意:我是 Eclipse Collections 的提交者。
我正在尝试计算 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();
}
}
我会这样:
- 创建
HashMap<String, Integer>
,键为组件,值为出现次数。 - 像您一样使用
while
浏览 json 文件。对于每个组件,检查哈希映射中是否存在 - 如果存在,则将值增加 1,如果不存在,则将新值 1 放在组件的键下。 - 循环打印所有键(组件)和值(重复计数)。
大功告成。
如果您愿意使用第三方库,可以使用来自 Guava 的 HashBag from Eclipse Collections, a HashBag from Apache Commons Collections or a HashMultiset。
您可以像任何其他集合一样将您的项目添加到 Bag
/Multiset
,他们会在内部为您跟踪计数。
注意:我是 Eclipse Collections 的提交者。