LyodMichael
LyodMichael

Reputation: 85

count dupplicated data on json file using java

am trying to count all the duplicate data from a json file, but i dont get the right count of the data, im thinking to arrange the data before i add it to a list but its possible to arrange json data? what i think for the ouput :

component : pensil : 5 
               pen : 1

here is my codes. some tips guys thanks.

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();
    }   
}

Upvotes: 1

Views: 255

Answers (2)

Donald Raab
Donald Raab

Reputation: 6706

If you're open to using a third-party library, you could use a HashBag from Eclipse Collections, a HashBag from Apache Commons Collections or a HashMultiset from Guava.

You can add your items to a Bag/Multiset like any other collection, and internally they will keep track of the count for you.

Note: I am a committer for Eclipse Collections.

Upvotes: 2

Martin Polak
Martin Polak

Reputation: 124

I would go like this:

  1. Create HashMap<String, Integer>, let key be component and value be number of occurences.
  2. Go thru the json file with while as you do. For every component check the presence in hash map - if it is present, increase value by 1, if not present, put new value 1 under the key of component.
  3. Print in cycle all keys (components) and values (count of duplicates).

You are done.

Upvotes: 1

Related Questions