首页 > 代码库 > Java Map List 的使用

Java Map List 的使用

项目中有一个需求是将年月分两行显示:

技术分享

java后台代码

创建一个demo,使用Map List 拆分年月:

package demo;

import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

public class Test {

public static void main(String[] args) {
// TODO Auto-generated method stub
String s1 = "2016-10";
String s2 = "2016-11";
String s3 = "2016-12";
String s4 = "2017-1";
List<String> sList = new ArrayList<String>();
sList.add(s1);
sList.add(s2);
sList.add(s3);
sList.add(s4);
System.out.println("初始年月sList: " + sList);

Map<String,Integer> yearsDic = getYearsAndCount(sList);
System.out.println("每一年下面的月份數yearsDic: " + yearsDic);

//建立年份和月份集合
List<String> yearList = new ArrayList<String>();
List<String> monthList = new ArrayList<String>();

for (int i=0; i< sList.size(); i++)
{
String year = sList.get(i).split("-")[0];
String month = sList.get(i).split("-")[1];
if(!yearList.contains(year))
{
yearList.add(year);
}
monthList.add(month);
}
System.out.println("年份集合yearList: " + yearList);
System.out.println("月份集合monthList: " + monthList);
}

/*返回年份集合,每一年占多少列*/
private static Map<String, Integer> getYearsAndCount(List<String> sList)
{
Map<String, Integer> yearCount = new HashMap<String, Integer>();
for (int i = 0; i < sList.size(); i++)
{
String year = sList.get(i).split("-")[0];
if (yearCount.containsKey(year))
{
Integer count = yearCount.get(year);
yearCount.put(year, count+1);//增加列
}else {
yearCount.put(year, 1);//初始值1
}
}
return yearCount;
}
}

控制台输出:

技术分享

 

项目用的是spring4.0,添加到视图:

 

/**列表
     * @param page
     * @throws Exception
     */
    @RequestMapping(value="/list")
    public ModelAndView list(Page page) throws Exception{
        
        ModelAndView mv = this.getModelAndView();

        mv.addObject("months", monthList);
        mv.addObject("yearsCount", yearsDic);
        mv.addObject("yearlist", yearsList);

        return mv;
    }

放到jsp中显示:

技术分享

 

Java Map List 的使用