0

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?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
user613114
  • 2,731
  • 11
  • 47
  • 73

1 Answers1

1

what do you think about this??

public static void main(String[] args) {
    String s1 = "1, 2, 3";
    String s2 = "a, b, c";
    Map<String, String> m = new HashMap<String, String>();
    String s1List [] = s1.split(",");
    String s2List [] = s2.split(",");
    for (int i = 0; i < s1List.length && i < s2List.length; i++) {
        m.put(s1List[i].trim(), s2List[i].trim());
    }
    System.out.println(m);
}
Abhishek
  • 2,485
  • 2
  • 18
  • 25