1. 程式人生 > >將List中某個欄位相同的資料相加(統計出現了幾次)

將List中某個欄位相同的資料相加(統計出現了幾次)

//取出初始資料
List<LdpaMtxfjlb> LdpaMtxfjlbList = ldpaMtxfjlService.selectAllInfo();

Map<String,Integer> map = new HashMap<>();
//將日期相同的資料進行相加
List<String> same = new ArrayList<>();//接收重複資料的ID
boolean flag = false;  //重複標誌
String name = "";  //map鍵值
int sum = 1;          //重複出現次數
for(LdpaMtxfjlb l:LdpaMtxfjlbList){   

for(String s:same){  //檢測是否出現重複資料
if(l.getId().equals(s)){
flag = true;  //發現重複ID則跳過此次迴圈
break;
}
}

if(flag){
flag = false;
continue;
}

name = CommUtil.getSimpleDateFormat(l.getDate());
for(LdpaMtxfjlb lm:LdpaMtxfjlbList){

if(l.getId().equals(lm.getId())){//不與自己比較
continue;
}else if(l.getDate().equals(lm.getDate())){//檢測相同日期的選項
sum ++;
same.add(lm.getId());
}
}
map.put(name, sum); //登記到map
sum = 1; //重置sum
}

for (Map.Entry<String,Integer> entry : map.entrySet()) { //遍歷輸出
 
   System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());  
}