java8的stream將一個List轉為按照某個欄位分組的map,(Map<String, List<Owner>>)
然後再按照 更新日期
欄位取分組的每個list裡最大的那個,Map<String, Owner>
最終得到一個map
List<Owner> ---> (Map<String, List<Owner>>) ----> Map<String, Owner>
1. Owner物件結構
import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.Date;
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Owner implements Serializable {
/**
* 成員名稱
*/
private String name;
/**
* 身份證號
*/
private String idcard;
/**
* 建立時間
*/
private Date createTime;
/**
* 更新時間
*/
private Date updateTime;
}
2. 處理過程
@Test
void testList() throws ParseException {
List<Owner> list = new ArrayList<>();
// 取得字串表示的Date物件
Date d1 = DateUtils.toDate("1662-05-04 22:22:22");
Date d2 = DateUtils.toDate("0599-01-23 00:00:00");
Date d3 = DateUtils.toDate("1328-10-21 11:11:11");
Owner o1 = Owner.builder().idcard("1001").updateTime(d1).name("康熙").build();
Owner o2 = Owner.builder().idcard("1001").updateTime(d2).name("李世民").build();
Owner o3 = Owner.builder().idcard("1001").updateTime(d3).name("朱元璋").build();
Owner o4 = Owner.builder().idcard("1002").updateTime(d1).name("張三").build();
Owner o5 = Owner.builder().idcard("1003").updateTime(d1).name("李四").build();
list.add(o1);
list.add(o2);
list.add(o3);
list.add(o4);
list.add(o5);
// 將List按照Owner物件的 idcard 欄位分組 得到map
Map<String, List<Owner>> listMap = list.stream().collect(Collectors.groupingBy(Owner::getIdcard));
// java8 Stream max函式使用的比較器:按照updateTime欄位比較
Comparator<Owner> comparator = Comparator.comparing(Owner::getUpdateTime);
// Map轉換,取得每個idcard的最後更新的物件(多取一)
Map<String, Owner> resultMap = new HashMap<>();
listMap.entrySet().stream().forEach(e-> {
Owner owner = e.getValue().stream().max(comparator).get();
resultMap.put(e.getKey(), owner);
});
// 最終得到 每個idcard一個物件的map
System.out.println(GsonUtils.toGson(resultMap));
3. 最終結果:
{
"1003":{
"name":"李四",
"idcard":"1003",
"updateTime":"1662-05-04 22:22:22"
},
"1002":{
"name":"張三",
"idcard":"1002",
"updateTime":"1662-05-04 22:22:22"
},
"1001":{
"name":"康熙",
"idcard":"1001",
"updateTime":"1662-05-04 22:22:22"
}
}