Java List 分組轉換

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;
		}
    	
	}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章