java - How to convert a csv to Hashmap if there are multiple values for a key ? (without using csv reader ) -


here link states reading of data csv hashmap. convert csv values hashmap key value pairs in java however, trying read file of csv, in there multiple values given key. eg:

key  -  value  fruit -  apple fruit -strawberry fruit -grapefruit vegetable -potatoe vegetable -celery 

where , fruit , vegetable keys.

i using arraylist<> store values. code writing able store keys , stores last corresponding value . so, when print hashmap , : fruit - [grapefruit] vegetable- [celery] how can iterate through loop, , store values?

following code, have written :

public class csvvaluereader {     public static void main(string[] args) throws ioexception {         map<string, arraylist<string>> mp=null;         try {                  string csvfile = "test.csv";                 //create bufferedreader read csv file                bufferedreader br = new bufferedreader(new filereader(csvfile));                string line = "";                stringtokenizer st = null;                 mp= new hashmap<string, arraylist<string>>();                 int linenumber = 0;                 int tokennumber = 0;                           //read comma separated file line line                            while ((line = br.readline()) != null) {                linenumber++;                              //use comma token separator                 st = new stringtokenizer(line, ",");                             while (st.hasmoretokens()) {                 tokennumber++;                               string token_lhs=st.nexttoken();                             string token_rhs= st.nexttoken();                              arraylist<string> arrval = new arraylist<string>();                 arrval.add(token_rhs);                              mp.put(token_lhs,arrval);                              }                         }                          system.out.println("final hashmap : "+mp);  } catch (exception e) {                system.err.println("csv file cannot read : " + e);              }      }  } 

currently, you're putting new arraylist in map each value find. replaces old list had particular key. instead, should use existing array list (if there), , add value it.

you should therefore replace this:

arraylist<string> arrval = new arraylist<string>(); arrval.add(token_rhs); mp.put(token_lhs,arrval); 

by this:

arraylist<string> arrval = mp.get(token_lhs); if (arrval == null) {     arrval = new arraylist<string>();     mp.put(token_lhs,arrval); } arrval.add(token_rhs); 

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -