【JAVA基础】Lambda-集合类处理

【JAVA基础】Lambda-集合类处理

 

java8中的Stream对集合功能进行了增强,以往我们经常对集合对象进行处理,比较繁琐。Stream提供了对集合对象的各种非常便利的、高效的聚合操作,通过lambda表达式提供了一些方便list操作的方法。

1. Stream的最核心的方法:collect

collect是一个将管道流的结果集到一个值的结束操作,这个值可以是集合、映射,或者一个值对象等。
其用法的核心就是使用Collectors工具类来实现,它是在为Collector服务,用于创建各种不同的Collector。Collectors的toMap方法用法如下:
(1)list 转 map

 

List<Person> list = new ArrayList();  
list.add(new Person(1, "haha"));  
list.add(new Person(2, "rere"));  
list.add(new Person(3, "fefe"));  
//获取映射的键和值的策略
Map<Integer, Person> mapp = list.stream().collect(Collectors.toMap(Person::getId, Function.identity()));  
System.out.println(mapp.get(1).getName());  
//如何获取映射的键和值的策略
Map<Integer, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName));  
System.out.println(map); 

如果key有冲突的时候的处理,在发生冲突的情况下,我们保留现有条目:

 

Map<Integer, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName,(existing, replacement) -> existing));  

(2)List 转 ConcurrentMap,treemap等
默认情况下,tomap()方法将返回哈希映射,同时我也可以返回其它映射:

 

return list.stream().collect(Collectors.toMap(Person::getId, Function.identity(),(o1, o2) -> o1, ConcurrentHashMap::new))); 

return list.stream().collect(Collectors.toMap(Person::getId, Function.identity(),(o1, o2) -> o1, TreeMap::new))); 

Collectors中的还有很多方法,如joining、toList、分组等,部分功能与Stream中的方法重合了,为了简化代码,完全不必采用Collectors实现,优先Stream方法。

2.通过Stream的filter方法可以过滤某些条件

 

//排除掉工号为201901的用户
List<User> userCommonList = userList.stream().filter(a -> !a.getJobNumber().equals("201901")).collect(Collectors.toList());

3.映射(map)

把一个序列映射成另一个序列,映射规则由一个函数制定。

 

result = list.stream().filter(i -> UN_LOGIN.equals(i.getRemark())).map(this::chg2CodeInfo).collect(Collectors.toList());
//函数
public CodeInfo chg2CodeInfo(TbCode tbCode)
{
    CodeInfo codeInfo = new CodeInfo();
    codeInfo.setCodeVal(tbCode.getCodeVal());
    codeInfo.setCodeDesc(tbCode.getCodeDesc());
    codeInfo.setRemark(tbCode.getRemark());
    return codeInfo;
}



作者:嘻洋洋
链接:https://www.jianshu.com/p/23ca34a4d9fe
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值