Collectors.toMap 根据字段去重

Collectors.toMap
在这里插入图片描述
map.merge
在这里插入图片描述

list.stream()
	// Collectors.toMap去重
	// 将list转为map
	.collect(Collectors.toMap(
	// id为key
	Entity -> entity.getId(),
	// 实体对象为value
	// Function.identity() 返回和输入相同的 等同于 t->t
	Function.identity(),
    // 先从map中get(第一个参数key),
    // 如果get的value为null,put(key,value),
    // 如果get的value不为空则根据(o,n)->o选择 新/旧 的value, 再put(k,v)
	(oldValue, newValue) -> oldValue))
	// 收集map的value集合
	.values().stream().collect(Collectors.toList());

可以理解为

Map<Long, Entity> map = new HashMap<>();
for (Entity entity : list) {
    map.putIfAbsent(entity.getId(), entity);
}
entityList = map.values().stream().collect(Collectors.toList());