0

我有一个查询字符串,它接收为January, February, March

我想用逗号分割字符串并将字符串放入HashMap,这样当我检索时我想获取并执行空检查字符串为January, February, March

我怎样才能做到这一点?

4

3 回答 3

1

您可以使用拆分功能:

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

然后您可以将其转换为 HashSet,例如:

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

或列表:

List<String> months = Arrays.asList(monthsArray)
于 2013-04-09T08:45:00.060 回答
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)

于 2013-04-09T08:47:19.857 回答
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
于 2013-04-09T09:14:56.150 回答