栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java8中stream的几种妙用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java8中stream的几种妙用

文章目录
      • 获取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 中 Object 某个属性去重
// 2.1 新建一个列表
studentList = studentList.stream().collect(
    collectingAndThen(
      toCollection(() -> new TreeSet<>(Comparator.comparing(Student::getName))), ArrayList::new));
// 2.2 通过filter()方法
private static  Predicate distinctByKey(Function keyExtractor) {
    Set seen = ConcurrentHashMap.newKeySet();
    return t -> seen.add(keyExtractor.apply(t));
};
studentList = studentList.stream().filter(distinctByKey(Student::getName)).collect(Collectors.toList());



转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号