Stream流

本文介绍了Java8中StreamAPI的五种主要操作:过滤(filter)、映射(map)、去重(distinct)、循环(forEach)以及转换(collect)到不同集合类型。通过实例展示了如何使用lambda表达式处理列表并操作User对象的属性。
摘要由CSDN通过智能技术生成

1,拦截

list.stream().filter()

//输出ID大于6的user对象
List<User> filetrUserList = userList.stream().filter(user -> user.getId() > 6).collect(Collectors.toList());
filetrUserList.forEach(System.out::println);

2,映射

list.stream().map()

把一个字段映射成一个新的集合使用

List<String> mapUserList = userList.stream().map(user -> user.getName() + "用户").collect(Collectors.toList());
mapUserList.forEach(System.out::println);

user -> user.getName:正则表达式,获取user的name值

3,去重

去除集合里重复的数据

list.stream().distinct()

List<String> distinctUsers =  userList.stream().map(User::getCity).distinct().collect(Collectors.toList());
distinctUsers.forEach(System.out::println);

::代表直接执行类的方法,直接使用,无需考虑方法里是否有属性

4,循环

list.stream().forEach()

userList.stream().forEach(user -> System.out.println(user));
userList.stream().filter(user -> "上海".equals(user.getCity())).forEach(System.out::println);

5,转换

转换成list集合

list.stream.collect(Collectors.toList())

List<Integer> idList = userList.stream().map(User::getId).collect(Collectors.toList()) ;

转换为map集合

list.stream.collect(Collectors.toMap(key,value))

Map<Integer,String> userMap = userList.stream().collect(Collectors.toMap(User::getId,User::getName));

转换为set集合

list.stream.collect(Collectors.toSet)

Set<String> citySet = userList.stream().map(User::getCity).collect(Collectors.toSet());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值