一个简单的Map与String的转换方法,比较实用的一段java代码
username'chenziwen^password'1234的字符串
[java] view plain copy print ?
1. /**
2. * 方法名称:transMapToString
3. * 传入参数:map
4. * 返回值:String 形如 username'chenziwen^password'1234
5. */
6. public static
7. java.util.Map.Entry entry;
8. new
9. for(Iterator iterator = map.entrySet().iterator(); iterator.hasNext();)
10. {
11. entry = (java.util.Map.Entry)iterator.next();
12. "'" ).append(null==entry.getValue()?"":
13. "^" : "");
14. }
15. return
16. }
/**
* 方法名称:transMapToString
* 传入参数:map
* 返回值:String 形如 username'chenziwen^password'1234
*/
public static String transMapToString(Map map){
java.util.Map.Entry entry;
StringBuffer sb = new StringBuffer();
for(Iterator iterator = map.entrySet().iterator(); iterator.hasNext();)
{
entry = (java.util.Map.Entry)iterator.next();
sb.append(entry.getKey().toString()).append( "'" ).append(null==entry.getValue()?"":
entry.getValue().toString()).append (iterator.hasNext() ? "^" : "");
}
return sb.toString();
}
username'chenziwen^password'1234的字符串转成Map
[java] view plain copy print ?
1. /**
2. * 方法名称:transStringToMap
3. * 传入参数:mapString 形如 username'chenziwen^password'1234
4. * 返回值:Map
5. */
6. public static
7. new
8. java.util.StringTokenizer items;
9. for(StringTokenizer entrys = new StringTokenizer(mapString, "^");entrys.hasMoreTokens();
10. null))
11. new StringTokenizer(entrys.nextToken(), "'");
12. return
13. }
/**
* 方法名称:transStringToMap
* 传入参数:mapString 形如 username'chenziwen^password'1234
* 返回值:Map
*/
public static Map transStringToMap(String mapString){
Map map = new HashMap();
java.util.StringTokenizer items;
for(StringTokenizer entrys = new StringTokenizer(mapString, "^");entrys.hasMoreTokens();
map.put(items.nextToken(), items.hasMoreTokens() ? ((Object) (items.nextToken())) : null))
items = new StringTokenizer(entrys.nextToken(), "'");
return map;
}