jdk1.8 新特性_Steam2

jdk 1.8 Stream 使用

主要有如下几种场景:

  • 1、group by (分组)

  • 2、order by (排序)

  • 3、where (筛选)

  • 4、distinct (去重)

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

  • 6、提取某个属性为列表

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

根据某个字段获得对象

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)));
复制代码
posted @ 2022-04-27 15:54  北方有鱼  阅读(350)  评论(0编辑  收藏  举报