Search code examples
javahashmapopencsv

How to parse the csv to hashmap grouping by column using opencsv


I am trying to use hashmap the col1 values to col2 values from a csv file using CSVREADER. But I am unable to find a logic to do so.

I want to do it through reading the CSV through CSVReader, looping the datalines and using arraylist and hashmap key and value(arraylist). I dont want to hardcode it..

I did something till the following. Unable to proceed further. Please help..

        CSVReader csvReader = new CSVReader(new FileReader(fileName),',','"',1);
        Map<String, List<String>> tableandcols = new HashMap<String, List<String>>();
        ArrayList<String> tablenames = new ArrayList<>();
        ArrayList<String> colnames = new ArrayList<>();
        while((row = csvReader.readNext()) != null) {
            tablenames.add(row[0]);
            colnames.add(row[1]);
            }

input data: 
State,City,Country
NJ,Trenton,US
NJ,Newark,US
NC,Cary,US
NC,Charlotte,US
GA,Atlanta,US

I want the data to be in hashmap as following
[<NJ,[Trenton,Newark]>
<NC,[Cary,Charlotte]>
<GA,[Atlanta]>]

Solution

  • You can try below piece of code :

        try
        {
          CSVReader csvReader = new CSVReader(new FileReader(fileName),',','"',1);
          Map<String, List<String>> tableandcols = new HashMap<String, List<String>>();
          while((row = csvReader.readNext()) != null) 
          {
            // If map contains state already, add the city to the values list
            if(tableandcols.containsKey(row[0]))
             { 
               tableandcols.get(row[0]).add(row[1);
             }
             // if map doesn't have this state as key, insert a key and value
             else {
               List<String> cities = new ArrayList<>();
               cities.add(row[1]);
               tableandcols.put(row[0], cities);
             }
          }
         } 
         catch(Exception e){
          // log exception
         }
    

    Alternatively, you can also use HeaderColumnNameTranslateMappingStrategy to map column values to java bean. Loop through the java beans list and aggregate cities based on state.