2013-04-09 18 views
0

我有收到爲January, February, March把逗號分隔的Collecton Object值

我想用逗號分割的字符串,並會把字符串中HashMap,所以,當我取回我想獲得一個查詢字符串並做一個空檢查字符串爲January, February, March

我該怎麼做?

+0

可以使用字符串的分割方法做到這一點。順便說一句,爲什麼HashMap?爲什麼不列出? – 2013-04-09 08:45:21

+0

把它放在HashMap中是什麼意思?你打算將所有逗號分隔的值存儲到Map中嗎?那麼我猜ArrayList會好起來的。 – 2013-04-09 08:46:30

+0

@ShreyosAdikari我將始終擁有最多三個值,所以我想爲每個值分配或放置名稱並按名稱提取。 – user75ponic 2013-04-09 09:20:38

回答

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 
+0

Pratik Singal,謝謝你,我試着調用'key.getInteger(「1」)',但是爲null。我想用某個名字來調用,這就是我尋找HashMap的原因。任何方式我可以打電話給1月1日,2月1日等。 – user75ponic 2013-04-09 09:43:05

1

您可以使用拆分功能:

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

然後你就可以將其轉換到HashSet,如:

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

或一個列表:

List<String> months = Arrays.asList(monthsArray) 
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)

+0

您無法在最終列表 monthList for for循環中進一步分配值。 – 2013-04-09 08:48:06

+0

只添加元素,引用不變;) – 2013-04-09 08:52:20

+0

明白了man .... :) – 2013-04-09 08:58:40