Java Collection How to - Put Comma separated values in Collecton Map Object








Question

We would like to know how to put Comma separated values in Collecton Map Object.

Answer

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/*w ww .j av a 2 s  .c om*/
public class Main {
  public static void main(String[] args) {
    String text = "A,B,C,D";
    
    String[] keyValue = text.split(",");
    
    Map<Integer, String> myMap = new HashMap<Integer, String>();
    for (int i = 0; i < keyValue.length; i++) {
      myMap.put(i, keyValue[i]);
    }
    
    Set keys = myMap.keySet();
    Iterator itr = keys.iterator();

    while (itr.hasNext()) {
      Integer key = (Integer) itr.next();
      String value = (String) myMap.get(key);
      System.out.println(key + " - " + value);
    }
  }
}

The code above generates the following result.