0

input data in a file given below

1985,Adv,Blue
1985,Adv,gill
1985,Adv,mon
1985,Cal,20
1985,Cal,25
1985,Cape,Din
1966,Ray,One
1966,Ray,bel
1966,Ray,Reb
1966,Sum,37
1966,Tar,Black
1966,Tar,Watch
1967,Yachts,Nut
1967,Yachts,Shark
1967,Cal,20
1967,Cal,25
1967,Cal,28

Expected output as a json file with formatted data like

{
    "1985" : {
        "Adv" : ["Blue", "gill", "mon"],
        "Cal" : ["20", "25"],
        "Cape" : ["Din"]
    },
    "1966" : {
        "Ray" : ["One", "bel", "Reb"],
        "Sum" : ["37"],
        "Tar" : ["Black", "Watch"]
    },
    "1967" : {
        "Yachts" : ["Nut", "Shark"],
        "Cal" : ["20", "25", "28"]
    }
}

I have more than 1000 lines of data. Need to use some loop. How to do this in java

1
  • What have you tried so far? Can you show your code? Commented Apr 6, 2020 at 17:39

1 Answer 1

2

You need to import an external library org.json.JSONObject

 File myObj = new File("test.txt");
            Scanner myReader = new Scanner(myObj);
            List<String> stringList = new ArrayList<>();
            while (myReader.hasNextLine()) {
                String data = myReader.nextLine();
                stringList.add(data);
            }
            Map<String, Map<String,List<String>>> mapStringToObject = new HashMap<>();
            for(String string : stringList){
                String[] data = string.split(",");
                if(!mapStringToObject.containsKey(data[0])){
                    Map<String,List<String>>  mapOfLists = new HashMap<>();
                    List<String> list = new ArrayList<>();
                    list.add(data[2]);
                    mapOfLists.put(data[1],list);
                    mapStringToObject.put(data[0],mapOfLists);
                }else{
                    if(!mapStringToObject.get(data[0]).containsKey(data[1])){
                        List<String> list = new ArrayList<>();
                        list.add(data[2]);
                        mapStringToObject.get(data[0]).put(data[1],list);
                    }else
                        mapStringToObject.get(data[0]).get(data[1]).add(data[2]);
                }
            }
            JSONObject json = new JSONObject(mapStringToObject);
            System.out.println(json);
            myReader.close();

test.txt

1985,Adv,Blue
1985,Adv,gill
1985,Adv,mon
1985,Cal,20
1985,Cal,25
1985,Cape,Din
1966,Ray,One
1966,Ray,bel
1966,Ray,Reb
1966,Sum,37
1966,Tar,Black
1966,Tar,Watch
1967,Yachts,Nut
1967,Yachts,Shark
1967,Cal,20
1967,Cal,25
1967,Cal,28
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Nice effort.

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.