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

7,362 阅读2分钟

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

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

Java8-Stream: no instance(s) of type variable(s) R exist so that void conforms to R

一、场景概述

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));

// 获得对象
// 这里会有'Optional.get()' without 'isPresent()' check的提示,可以换为User user = min.orElse(null);
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);

筛选掉name为null的数据

userList.stream()
        .filter(u -> u.getName() != null)
        .collect(Collectors.toList());

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)
	);

根据某字段去重(不乱序)

  • 自定义一个方法
static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Map<Object,Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
  • 去重
list.stream().filter(distinctByKey(b -> b.getName())).collect(Collectors.toList());

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)));

2.7、计算

计算某个属性的和

Long allCount = userList.stream().mapToLong(User::getScore).sum();



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