文章目录
- 获取List集合中的某一种属性
- 由list生成map信息
- List排序
- List去重
获取List集合中的某一种属性
// 获取设备列表中所有的小区
List communityIds = equipmentList.stream()
.map(Equipment::getCommunityId)
.collect(Collectors.toList());
由list生成map信息
// 从小区返回信息中, 生成对应的<小区Id:小区信息>
Map communityMap = communityResponseList.stream()
.collect(Collectors.toMap(CommunityResponse::getId, e -> e));
List排序
// 按照自然顺序进行排序
list.stream().sorted();
// 按照自然顺序进行方向排序
list.stream().sorted(Comparator.reverseOrder());
// 按照对象的某一种属性对对象进行排序
list.stream().sorted(Comparator.comparing(Student::getAge));
// 按照对象的某一种属性对对象进行反向排序
list.stream().sorted(Comparator.comparing(Student::getAge).reversed);
List去重
// 1. distinct()
// 使用hashCode()和equals()去重
// 1.1 对于String去重
List stringList = new ArrayList();
...
stringList = stringList.stream().distinct().collect(Collectors.toList());
// 1.2 对于实体类列表去重
// 代码中我们使用了 Lombok 插件的 @Data注解,可自动覆写 equals() 以及 hashCode() 方法。
studentList = studentList.stream().distinct().collect(Collectors.toList());
// 2. 根据 List