string - Reading from a csv file and separating key and value and returning a map in java -


i'm reading csv file has column contains key value pair in 1 of columns. sample csv file:

country    product    baseurl              paramandmacro usa        oil        http://usa.com      key={value}&key2={value2}&key3={value3} 

i'm attempting split column called paramandmacro , store in hashmap key value pair. first attempt, successful @ splitting string using split function:

public map<string, string> splitstring(string s) {     // string s represents paramandmacro     string[] split = s.split("=|\\&");     int length = split.length;     map<string, string> maps = new hashmap<>();     (int i=0; i<length; i+=2){           maps.put(split[i], split[i+1]);      }      return maps; } 

this works doesn't check corner cases. such "key={value}&key2={value2}&key3=" or "key={value}&key2={value2}&key3=&" throw exception. if value empty store object key , empty value. ex: {key3=}. if key missing not store in map, i.e use logger report error, skip , continue. far have attempted 1 pass fail check if key missing. below implementation , how algorithm , if it's efficient.

so implemented split function below:

public map<string, string> splitstring(string s){  map<string, string> maps = new hashmap<>();  int length = s.length();  stringbuilder sb = new stringbuilder();  string key = "";  string value = "";  char prev = ' '; (int i=0; i<length; i++) {     char = s.charat(i);     if ( != '=' && != '&' && prev != a) {            sb.append(a);               }      else if( == '=' && prev != && prev != '&') {           key = sb.tostring();           sb = new stringbuilder();       }      else if (a=='&' && prev != && prev != '=') {           value = sb.tostring();           sb = new stringbuilder();           maps.put(key, value);             }     else if (prev=='=' && == '&') {           value = "";           maps.put(key, value);           sb = new stringbuilder();     }             prev = a;     }     return maps; } 

**note: ** reading csv file. parameters , macros long , wanted know if algorithm efficient in 1 pass.

expected outputs

key={value}&key2={value2}&key3=& is:

output: {key={value}, key2={value2}, key3=}

key={value}&key2={value2}&key3= is:

output: {key={value}, key2={value2}, key3=}

key={value}&{value2}&key3= is:

output: {key={value}, key3="}

={value}&key2={value2}&key3= is:

output: {key2={value2}, key3=}


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -