Java hashmap from python dict command?
I have a weird problem that I don't fully understand how to solve. Could someone please give me some pointers on hashmaps?
I have a variable:
/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,r开发者_开发知识库ed,green,purple"
I basically want 10.21,12.12,43.12,12.10 to be associated with blue,red,green,purple (in the order displayed)
In python I created a method that does this with:
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(',')))
Not sure how to do this in java. So far I have:
URL imgURL = new URL (imgTag);
String[] result = imgURL.getFile().split("&");
for (int x=0; x<result.length; x++)
System.out.println(result[x]);
This gives me:
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,
At this point I'm confused how to link static_labels and static_xvalues values.
Thanks so much. Any pointers would be awesome.
You want to look at StringTokenizer
Something like this (assuming you stored the labels into the String 'static_labels' and the values in the String '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()));
}
Look at using java.util.HashMap. Let's say you have stored the static_xvalues and static_labels request parameters into corresponding string variables. Something like the following will create the mapping for you:
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]);
}
You do not say if the xvalues need to be stored as floats or not. If so, you will need to convert the vals array into a Float (or Double) array first, and modify the HashMap instantiation accordingly:
HashMap<String,Float> = new HashMap<String,Float>();
精彩评论