0
点赞
收藏
分享

微信扫一扫

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

Fifi的天马行空 2022-04-29 阅读 66
java

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

  • 基础语法参考
    Java8新特性:HashMap优化、lambda、Stream等新特性详解

  • 遇到问题及解决参考
    这个文章访问量是真多,应该这个错比较常见,大家通过搜索引擎搜到了它
    Java8-Stream: no instance(s) of type variable(s) R exist so that void conforms to R

一、场景概述

1.1、Stream的作用

1.2、使用场景

主要有如下几种场景:

二、Tips

2.1、group by

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

2.2、order by

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、条件筛选

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

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());
userList.stream()
    .collect(Collectors.toMap(User::getMenuId, User::getMenuName)));
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等新特性详解

举报

相关推荐

0 条评论