java8中stream的几种妙用

本文详细介绍了如何在Java中对List集合进行操作,包括提取属性到新的List,由List生成Map,按特定属性进行升序和降序排序,以及使用distinct和自定义方式实现去重。这些方法在处理数据时非常实用。
摘要由CSDN通过智能技术生成

获取List集合中的某一种属性

// 获取设备列表中所有的小区
List<Long> 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<String> stringList = new ArrayList<String>();
...
stringList = stringList.stream().distinct().collect(Collectors.toList());
// 1.2 对于实体类列表去重
// 代码中我们使用了 Lombok 插件的 @Data注解,可自动覆写 equals() 以及 hashCode() 方法。
studentList = studentList.stream().distinct().collect(Collectors.toList());

// 2. 根据 List<Object> 中 Object 某个属性去重
// 2.1 新建一个列表
studentList = studentList.stream().collect(
    collectingAndThen(
      toCollection(() -> new TreeSet<>(Comparator.comparing(Student::getName))), ArrayList::new));
// 2.2 通过filter()方法
private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
    Set<Object> seen = ConcurrentHashMap.newKeySet();
    return t -> seen.add(keyExtractor.apply(t));
};
studentList = studentList.stream().filter(distinctByKey(Student::getName)).collect(Collectors.toList());

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值