在Collection Object中放置逗号分隔值

时间:2013-04-09 08:42:59

标签: java collections

我有一个查询字符串,收到January, February, March

我想用逗号分割字符串并将字符串放在HashMap中,这样当我检索时我想得到并执行null检查字符串为January, February, March

我该怎么做?

3 个答案:

答案 0 :(得分:1)

您可以使用拆分功能:

String[] monthsArray= yourString.split(",");

然后你可以将它转换为HashSet,如:

Set<String> months = new HashSet<String>(Arrays.asList(monthsArray));

或列表:

List<String> months = Arrays.asList(monthsArray)

答案 1 :(得分:1)

尝试类似的东西 -

    final String input = "January, February, March, ...";
    final String[] months = input.split(",");
    final List<String> monthList = new ArrayList<String>();
    for(String month : months) {
        monthList.add(month);
    }

您甚至可以直接从数组转换为列表,请查看Collections Framework API。

编辑:monthList=Arrays.asList(months)

答案 2 :(得分:1)

You can use the following code to store the months in a hash map.   

 import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.Set;
    import java.lang.String;

    public class strings {
        public static void main(String [] args){
            String text = "jan,feb,march,april";
            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();

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

The out put will be-
0 - jan
1 - feb
2 - march
3 - april


Further you can perform the check that you want