The stream of java8 converts a List into a map grouped by a field, (Map<String, List<Owner>>)
Then according to the 更新日期
field, take the largest one in each list of the group, Map<String, Owner>
end up with a map
List<Owner> ---> (Map<String, List<Owner>>) ----> Map<String, Owner>
1. Owner object structure
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. Processing
@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. Final result:
{
"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"
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。