Java List<Bean> 分组转换

来源:互联网 发布:网络大电影制作流程 编辑:程序博客网 时间:2024/06/05 07:15

1. 什么是List<Bean> 分组转换, 请看如下数据结构,getter and setter 方法省略

 

    待分组数据结构

public class CommuneResourceBean implements java.io.Serializable {    private Integer id;    private Integer productId;    private String productName;    private Date priceDate;    private double cashRebate;    private Double communePrice;    private Double communeMinus;}

    分组数据结构

public class CommuneResourceV4 implements java.io.Serializable{    private String date;    private List<CommuneResourceV4PriceBean> prices;}public class CommuneResourceV4PriceBean implements java.io.Serializable{     private String productName;    private double cashRebate;    private Double communePrice;    private Double communeMinus;}

现在将List<CommuneResourceBean> list转换成List<CommuneResourceV4> v4list 的数据结构,  分组依据是priceDate

        if(list.size()>0){    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");    for(CommuneResourceBean asm : list){    Date priceDate = asm.getPriceDate();    String priceDateStr = df.format(priceDate);    int index = containDate(v4list,priceDateStr);    CommuneResourceV4PriceBean bean = new CommuneResourceV4PriceBean();    String simpleProductName = productName;                                        bean.setProductName(simpleProductName);    bean.setCashRebate(asm.getCashRebate());    bean.setCommunePrice(asm.getCommunePrice());    bean.setCommuneMinus(asm.getCommuneMinus());    if(index>=0){    CommuneResourceV4 v4 = v4list.get(index);    List<CommuneResourceV4PriceBean> priceBeanList = v4.getCourses();    priceBeanList.add(bean);    }else{    CommuneResourceV4 v4 = new CommuneResourceV4();    List<CommuneResourceV4PriceBean> priceBeanList = new ArrayList<CommuneResourceV4PriceBean>();    priceBeanList.add(bean);    v4.setDate(priceDateStr);    v4.setCourses(priceBeanList);    v4list.add(v4);    }        }            }        return v4list;

判断函数


    /**     * 判断某个 List<CommuneResourceV4> v4list  是否包含CommuneResourceV4.priceDate为priceDateStr的元素     * @param priceDateStr      * @param v4list      * @param v4list     * @param priceDate     * @return index 代表 list表中所在的位置,默认-1     */    private int containDate(List<CommuneResourceV4> v4list, String priceDateStr) {int index=-1;    if(v4list.size()>0){//如果v4list包含日起为priceDate的数据  将asm 写入    for(CommuneResourceV4 v4 : v4list){index++;if(v4.getDate().equals(priceDateStr)){return index;}}    return -1;}else{return index;}    }