1. 程式人生 > >Java List 分組轉換

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