如何將List中存放的實體按照某個字段進行分組呢?來看看下面的例子,假如實體中有個字段叫批次號,咱們將具備相同批次號的實體放在一塊兒,那麼怎麼實現呢?看下面的代碼:java
能夠定義個Map,Map的key用於存放異常批次號,value存放實體集合List<TmExcpNewVo>。循環要排序的Listapp
[java] view plain copyspa
- /**
- * 按照異常批次號對已開單數據進行分組
- * @param billingList
- * @return
- * @throws Exception
- */
- private Map<String, List<TmExcpNewVo>> groupBillingDataByExcpBatchCode(List<TmExcpNewVo> billingList) throws Exception{
- Map<String, List<TmExcpNewVo>> resultMap = new HashMap<String, List<TmExcpNewVo>>();
-
- try{
- for(TmExcpNewVo tmExcpNew : billingList){
- if(resultMap.containsKey(tmExcpNew.getExcpbatch())){//map中異常批次已存在,將該數據存放到同一個key(key存放的是異常批次)的map中
- resultMap.get(tmExcpNew.getExcpbatch()).add(tmExcpNew);
- }else{//map中不存在,新建key,用來存放數據
- List<TmExcpNewVo> tmpList = new ArrayList<TmExcpNewVo>();
- tmpList.add(tmExcpNew);
- resultMap.put(tmExcpNew.getExcpbatch(), tmpList);
- }
- }
-
- }catch(Exception e){
- throw new Exception("按照異常批次號對已開單數據進行分組時出現異常", e);
- }
-
- return resultMap;
- }