日期:2014-05-20 浏览次数:20884 次
StringBuffer jsonStrBuf = new StringBuffer("["); String[] arr = { "2011-11", "2012-02", "2012-03", "2012-04", "2012-05", "2012-06", "2012-07" }; List<String> list = Arrays.asList(arr); Map<String, List<String>> map = new HashMap<String, List<String>>(); for (String str : list) { String y = str.substring(0, 4); String m = str.substring(5); if (map.containsKey(y)) { map.get(y).add(m); } else { List<String> l = new ArrayList<String>(); l.add(m); map.put(y, l); } } for (String key : map.keySet()) { jsonStrBuf.append("{'year':" + key); jsonStrBuf.append(",'month':" + Arrays.toString((map.get(key).toArray(new String[0]))) + "},"); } System.out.println(jsonStrBuf.delete(jsonStrBuf.length() - 1, jsonStrBuf.length()).append("]"));
------解决方案--------------------
for example
list = [2011-11, 2012-02, 2012-03, 2012-04, 2012-05, 2012-06, 2012-07]; Map<String, List<String>> map = new HashMap<String, List<String>>(); for (String s : list) { //把list解析,结果存到map里 String[] sa = s.split("-"); if (!map.containsKey(sa[0])) map.put(sa[0], new ArrayList<String>()); map.get(sa[0]).add(sa[1]); } StringBuilder buf = new StringBuilder(); for (Map.Entry<String, List<String>> e : map.entrySet()) { buf.append("{'year:").append(e.getKey()).append(",'month':["); for (String s : e.getValue()) { buf.append("'").append(s).append("',"); } buf.delete(buf.length()-1, buf.length()); buf.append("},"); } buf.delete(buf.length()-1, buf.length()); System.out.println(buf);