java8采用stream对集合的常用操作

该博客记录了Java8采用Stream对集合的常用操作,包括对象集合的分组(两种形式)、去重操作、使用map得到特定结构、用filter进行数据筛选、作循环及限制数量,还能求最大值和最小值。

记录一下java8采用stream对集合的常用操作

User :{
	id,
	name,
	age
}

1.对象集合的分组(有两种形式)
示例:List userList,根据id分组,可以分组成为两种格式的map
(1)Map<id,User>

Map<id,User> map = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));

(2)Map<id,List>

Map<id,List<User>> = userList.stream().collect(Collectors.groupingBy(User::getId));

2.去重操作
对List 实现去重,distinct关键字

示例:userList= userList.stream().distinct().collect(Collectors.toList());

3.stream的map
主要用于得到特定的结构
例如:List userList,我向得到User Id的集合

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

4.stream的filter
主要用于数据的筛选。
例1:一个条件的筛选,删选id>5的User

List<UserList> userList = userList.stream.filter(i->i.getId()>5).collect(Collectors.toList());

例2:两个条件的删选用&&连接就行,删选id>5年纪>10的User

List<UserList> userList = userList.stream.filter(i->i.getId()>5&&i.getAge()>10).collect(Collectors.toList());

5.用来作循环

userList.stream().forEach(user -> System.out.println("姓名:" + user.getName()));

当然也可以加个limit限制数量

userList.stream().limit(2).forEach(user -> System.out.println("姓名:" + user.getName()));

6.最大值最小值

 int maxAge = userList.stream().mapToInt(User::getAge).max().getAsInt();
 int minAge = userList.stream().mapToInt(User::getAge).min().getAsInt();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值