I have two comma separated strings. I wish to put these values in map by binding values index by index. One way to do is using following example:
package com.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class StringToMap {
public static void main(String[] args) {
String s1 = "1, 2, 3";
String s2 = "a, b, c";
Map<String, String> m = new HashMap<String, String>();
List<String> s1List = new ArrayList<String>(Arrays.asList(s1.split(",")));
List<String> s2List = new ArrayList<String>(Arrays.asList(s2.split(",")));
for (int i = 0; i < s1List.size(); i++) {
m.put(s1List.get(i).trim(), s2List.get(i).trim());
}
System.out.println(m);
}
}
Result is: {3=c, 2=b, 1=a}. Is there any other efficient/best way to do this?