2011-04-24 91 views
0

我有一個奇怪的問題,我不完全明白如何解決。有人能給我一些關於hashmaps的指示嗎?來自python dict命令的Java hashmap?

我有一個變量:

/servlet/charting?base_color=grey&chart_width=288&chart_height=160&chart_type=png&chart_style=manufund_pie&3DSet=true&chart_size=small&leg_on=left&static_xvalues=10.21,12.12,43.12,12.10,&static_labels=blue,red,green,purple" 

我基本上要10.21,12.12,43.12,12.10與藍色,紅色,綠色,紫色相關聯(在順序顯示)

在Python中我創建了一個這樣做的方法:

def stripChart(name): 
    name = str(name) 
    name = urlparse.urlparse(name) 
    name = cgi.parse_qs(name.query) 
    name = dict(zip(name['static_labels'][0].split(','), name['static_xvalues'][0].split(','))) 

不知道如何在java中做到這一點。到目前爲止,我有:

URL imgURL = new URL (imgTag); 
String[] result = imgURL.getFile().split("&"); 
for (int x=0; x<result.length; x++) 
    System.out.println(result[x]); 

這給了我:

chart_width=288 
chart_height=160 
chart_type=png 
chart_style=manufund_pie 
3DSet=true 
chart_size=small 
leg_on=left 
static_xvalues=10.21,12.12,43.12,12.10, 
static_labels=blue,red,green,purple, 

在這一點上我很困惑如何鏈接static_labels和static_xvalues值。

非常感謝。任何指針都會很棒。

回答

0

你想看看StringTokenizer

像這樣的東西(假設你存儲在標籤爲字符串「static_labels」和字符串「static_xvalues」值):

HashMap<String, Double> colorMap = new HashMap<String, Double>(); 
StringTokenizer labelTok = new StringTokenizer(static_labels, ","); 
StringTokenizer valuesTok = new StringTokenizer(static_xvalues, ","); 
while(labelTok.hasMoreElements()){ 
    assert(valuesTok.hasMoreElements()); 
    colorMap.put(labelTok.nextElement(), Double.parseDouble(valuesTok.nextElement())); 
} 
0

看看使用java.util.HashMap中。假設您已將static_xvalues和static_labels請求參數存儲到相應的字符串變量中。像下面的內容將創建的映射關係對你:

String[] vals = static_xvalues.split(","); 
String[] labels = static_labels.split(","); 
HashMap<String,String> map = new HashMap<String,String>(); 
for (int i=0; i < vals.length; ++i) { 
    map.put(labels[i], values[i]); 
} 

你不說,如果xvalues需要被存儲爲浮動與否。如果是這樣,您需要首先將vals數組轉換爲Float(或Double)數組,然後相應地修改HashMap實例:

HashMap<String,Float> = new HashMap<String,Float>();