按月份分组数据处理

语言 Java
实现内容是一列带日期的数据分组成一个月一组的形式(提前要求是数据得按时间从小到大排序)

  • 数据结构
#  time 是Date日期类型
[
    {
        "time": "2019-01-01",
        "title": "这是20190101"
    },
    {
        "time": "2019-01-02",
        "title": "这是20190102"
    },
    {
        "time": "2019-02-01",
        "title": "这是20190201"
    },
    {
        "time": "2019-03-01",
        "title": "这是20190301"
    },
    {
        "time": "2019-03-02",
        "title": "这是20190302"
    },
    {
        "time": "2019-03-03",
        "title": "这是20190303"
    }
]
        
  • 方法
List> result= Lists.newLinkedList();
SimpleDateFormat sf=new SimpleDateFormat("yyyy年MM月");
for (int i = 0; i < list.size(); i++) {                     //list 格式 : List Data就是上面json格式
    Map params= Maps.newHashMap();
    String time=sf.format(list.get(i).getTime());
    List children= Lists.newLinkedList();
    for (int j = i; j < list.size(); j++) {
        Data data=list.get(j);
        if (time.equals(sf.format(data.getTime()))){
            children.add(data);
        }else{
            break;
        }
        i=j;
    }
    params.put("time",time );
    params.put("data",children);
    result.add(params);
}
return result;
  • 效果
[
    {
        "data": [
            {
                "time": "2019-01-01",
                "title": "这是20190101"
            },
            {
                "time": "2019-01-02",
                "title": "这是20190102"
            }
        ],
        "time": "2019年01月"
    },
    {
        "data": [
            {
                "time": "2019-02-01",
                "title": "这是20190201"
            }
        ],
        "time": "2019年02月"
    },
    {
        "data": [
            {
                "time": "2019-03-01",
                "title": "这是20190301"
            },
            {
                "time": "2019-03-02",
                "title": "这是20190302"
            },
            {
                "time": "2019-03-03",
                "title": "这是20190303"
            }
        ],
        "time": "2019年03月"
    }
]

你可能感兴趣的:(按月份分组数据处理)