实用宝典:Java8 Stream实用小技巧记录

最近发现这个Stream用的还是挺多的,基础语法掌握了,但是遇到实际场景的时候,又需要浪费很多时间才能写出来,所以对常用场景的写法进行总结,方便真实场景中快速应用。

另外关于基础语法和遇到的错误,可以参看我的其他文章

一、场景概述

1.1、Stream的作用

我们使用Stream主要是替换臃肿的for循环,对集合进行各种sao操作

1.2、使用场景

主要有如下几种场景:

1、group by (分组)

2、order by (排序)

3、where (筛选)

4、distinct (去重)

5、appLy (根据某个属性进行各种操作)

6、提取某个属性为列表

二、Tips

2.1、group by

根据性别进行分组

userList.stream()
    .collect(Collectors.groupingBy(User::getSex));

2.2、order by

按照用户年龄进行排序(升序/降序)并且取top3

userList.stream()
    .sorted(Comparator.comparing(User::getAge).reversed())
    .limit(3)
    .collect(Collectors.toList());

2.3、where

2.3.1、最值筛选

获得某个属性最大/最小的对象

// 最小
Optional<User> min = userList.stream()
    .min(Comparator.comparing(User::getAge));
// 最大
Optional<User> max = userList.stream()
    .max(Comparator.comparing(User::getAge));

// 获得对象
User user = min.get();

2.3.2、条件筛选

筛选年龄小于30岁的用户

userList.stream()
    .filter(e -> e.getAge() < 30)
    .collect(Collectors.toList());

选择用户年龄> 20 且性别为 男性的(sex=1)


userList.stream()
    .filter(u -> u.getAge() > 20 && u.getSex() == 1)
    .collect(Collectors.toList());

查询第一个姓名叫"李华"的用户

userList.stream().
    filter(u -> u.getName().equals("小明"))
    .findFirst().orElse(ll);

2.4、distinct

获取所有的用户名,并去重

userList.stream()
    .map(User::getName)
    .distinct()
    .collect(Collectors.toList());

根据某字段去重

memberListAll.stream()
    .collect(Collectors.collectingAndThen(
                        Collectors.toCollection(
                () -> new TreeSet<>(Comparator.comparing(WorkWxUserInfoVO :: getUserid))), ArrayList::new)
    );

2.5、apply

给某个属性批量赋值

userList.forEach(e -> {
            e.setName("hello");
        });

对某个字段进行处理

userList.stream()
    .map(user -> {user.setName(user.getName().replaceAll("\u0000", "")); return user;})
    .collect(Collectors.toList());

根据某个字段获得对象

List<User> userList = userIds.stream()
            .map(id -> {
                User user = userService.getUserById(id);
                return user;
            })
            .collect(Collectors.toList());

2.6、提取属性

提取单个属性:获取所有的用户名,并去重

userList.stream()
    .map(User::getName)
    .distinct()
    .collect(Collectors.toList());

提取多个属性:将menuId和menuName组成map(menuId唯一)

userList.stream()
    .collect(Collectors.toMap(User::getMenuId, User::getMenuName)));

提取多个属性:将menuId和menuName组成map(menuId不唯一)

userList
    //去重
    .stream().collect(Collectors.collectingAndThen(Collectors.toCollection(
                                () -> new TreeSet<>(Comparator.comparing(User :: getMenuId))), ArrayList::new))
    //转map
    .stream().collect(Collectors.toMap(User::getMenuId, User::getMenuName)));



以上仅记录最常见的几个场景,更多场景请参看:Java8新特性:HashMap优化、lambda、Stream等新特性详解

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值