1

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();
    }   
}
1
  • What is the content of your input file? Commented Apr 18, 2017 at 8:26

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

than you @martin ill try.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.