I have an String Array which would be like:
String [] paramEnv = {"key1=value1","key2=value2","key2=value2"};
Now I need to convert it to HashMap.
I have written two methods for it, I want to know which one is better in terms of efficiency.
Method 1:
String param = "";
String paramName = "";
String paramValue = "";
if ((null != paramEnv) && (paramEnv.length > 0)) {
for (int i = 0; i < paramEnv.length; i++) {
param = paramEnv[i];
int indexOfEqualTo = param.indexOf("=");
paramName = param.substring(0, indexOfEqualTo);
paramValue = param.substring(indexOfEqualTo + 1);
hmKeyValFromParamEnv.put(paramName, paramValue);
}
}
return hmKeyValFromParamEnv;
Method 2:
String param = "";
String paramName = "";
String paramValue = "";
if ((null != paramEnv) && (paramEnv.length > 0)) {
for (int i = 0; i < paramEnv.length; i++) {
param = paramEnv[i];
paramName = (param.split("="))[0];
paramValue = (param.split("="))[1];
hmKeyValFromParamEnv.put(paramName, paramValue);
}
}
return hmKeyValFromParamEnv;
Please let me know for any better implementation as well.
split()two times, call it one time and store the result. Also, set a limit to yoursplit().for(String s : paramEnv) { String[] st = s.split("="); map.put(st[0], st[1]); }=character ... they should both be avoided (or improved).