0

I have a table data in CSV format. First row contains all column names(keys) and all subsequent rows are records(values) as shown below:

ID,Name,Contact,Address
1,Alex,987654321,CA USA
2,Bob,4489398,LA USA
3,Marley,7236487,Washington

I am reading this file and trying to store the records as key value pair in LinkedHashMap. Here is my code to show what I am trying to do. My question is written in the code as comment.

public static void readCSV() throws IOException {

    BufferedReader br = new BufferedReader(new FileReader("table.csv"));

    Map<String, ArrayList<String>> map = new LinkedHashMap<>();

    String line = br.readLine();
    String[] keys = line.split(",");

    /*insert all keys with a corresponding empty arraylist as value to store
    all values of a particular key. ie each arralist will contain all values
    of individual columns. Since it is a linkedhashmap, keys are stored in 
    same order as they appear in the csv file*/

    for (String key : keys) {
        map.put(key, new ArrayList<String>());
    }

    while((line = br.readLine())!=null){
        String[] values = line.split(",");

        for (String value : values) {

            /*here I want to get the arraylists sequentially to store value.
            I know the first value goes in the first arraylist, second goes
            to second arraylist and so on.

            Is there a way to do this without using the key here??
            */

        }
    }
}
2
  • Why this data structure and not a map key -> columnIndex and a list of String[] (one per row)? Commented Jun 23, 2016 at 7:32
  • It could be better to parse every row to a custom object and put them into a list. Commented Jun 23, 2016 at 7:42

1 Answer 1

1

You can use an Iterator to iterate over the values of your Map :

while((line = br.readLine())!=null){
    String[] values = line.split(",");

    Iterator<ArrayList<String>> iter = map.values().iterator ();
    for (String value : values) {

        if (iter.hasNext()) {
            iter.next().add(value);
        }

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

Comments

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.