How can I obtain values of key-value pair from a Hashmap?
mylogger.info("original request start: "+request.getQueryString());
System.out.println("Query1:" + request.getQueryString());
QueryStats queryStats=new QueryStats();
Map parameterMap = request.getParameterMap()==null? null:new HashMap(request.getPa开发者_如何学PythonrameterMap());
System.out.println("Query2:" + parameterMap);
Collection newParamsValue=parameterMap.values();
Object newParams[]=newParamsValue.toArray();
StringBuffer strParam=new StringBuffer() ;
int l=newParams.length;
for(int i=0;i<l;i++){
**strParam=strParam.append((StringBuffer)newParams[i]);**
}
I want to get all the values into a string. How can I get it?
The parameter map is a Map<String, String[]>
. The proposed Object[]#toString()
answers will not work at all. You need to loop over the String[]
as well. Also, you have to URL-encode the key-value pairs in order to create a proper HTTP query string. Here's how it should be done:
public static String toQueryString(Map<String, String[]> params) {
StringBuilder queryString = new StringBuilder();
for (Entry<String, String[]> param : params.entrySet()) {
for (String value : param.getValue()) {
if (queryString.length() > 0) {
queryString.append("&");
}
queryString
.append(URLEncoder.encode(param.getKey(), "UTF-8"))
.append("=")
.append(URLEncoder.encode(value, "UTF-8"));
}
}
return queryString.toString();
}
Use this as follows
Map<String, String[]> params = request.getParameterMap();
String queryString = toQueryString(params);
// ...
use StringBuilder:
StringBuilder sb = new StringBuidler();
for(int i=0;i<l;i++){
sb.append(newParams[i].toString());
}
a slight variation on previous suggestion:
StringBuilder sb = new StringBuilder();
for (Object o : parameterMap.values()) {
String[] parameterValues = (String[]) o;
for ( String parameterValue : parameterValues) {
sb.add(parameterValue);
}
}
精彩评论