package com.test;import com.xbz.common.utils.XDateUtil;
import lombok.Data;import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;/*** @title 集合对象分组并组内编号* @description 应用场景 : 一组订单 , 按照天为单位分组 , 汇总每天下单的数量 , 并且每天的订单按照下单顺序依次编号*/
public class XTest1 {public static void main(String[] args) {List<Order> orderList = new ArrayList<>();Order o1 = new Order();o1.setCreateTime(1533000000000L);//2018-07-31 09:20:00o1.setCreateTimeDesc(XDateUtil.long2Str(o1.getCreateTime(), "yyyyMMdd"));orderList.add(o1);Order o2 = new Order();o2.setCreateTime(1533442332000L);//2018-08-05 12:12:12o2.setCreateTimeDesc(XDateUtil.long2Str(o2.getCreateTime(), "yyyyMMdd"));orderList.add(o2);Order o3 = new Order();o3.setCreateTime(1533443456000L);//2018-08-05 12:30:56o3.setCreateTimeDesc(XDateUtil.long2Str(o3.getCreateTime(), "yyyyMMdd"));orderList.add(o3);Order o4 = new Order();o4.setCreateTime(1533888888000L);//2018-08-10 16:14:48o4.setCreateTimeDesc(XDateUtil.long2Str(o4.getCreateTime(), "yyyyMMdd"));orderList.add(o4);Map<String, List<Order>> map = orderList.stream().collect(Collectors.groupingBy(Order::getCreateTimeDesc));//根据createTimeDesc进行分组map.values().forEach(value -> value.sort(Comparator.comparing(Order::getCreateTime)));map.values().forEach(value -> value.forEach(v -> v.setSerialNumber(value.indexOf(v) + 1)));//对每组的订单进行排序然后编号orderList = map.entrySet().stream().flatMap(v -> v.getValue().stream()).collect(Collectors.toList());//将处理后的map重新转换为listorderList.forEach(o -> System.out.println(o.getCreateTime() + " : " + o.getCreateTimeDesc() + " : " + o.getSerialNumber()));}
}@Data
class Order {private Long createTime;private String createTimeDesc;private Integer serialNumber;
}