ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

jdk1.8 新特性_Steam2

2022-04-27 16:01:18  阅读:251  来源: 互联网

标签:toList jdk1.8 stream Collectors collect 特性 userList User 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)));
复制代码

标签:toList,jdk1.8,stream,Collectors,collect,特性,userList,User,Steam2
来源: https://www.cnblogs.com/123-shen/p/16199306.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有