[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
业务开发中会运用到很多的List<T>集合数据类型,存放我们需要的业务数据,比如说有个产品产量信息表T,业务需要用柱状图展示每个产品每个月的产量图示,那我们定义了一个实体类ProductVO来传递这些数据,包含了月份month,总数count,产品pro,通过dao.xml中对产量信息表进行SQL编程,将产量数按月份和产品分组求和,最终返回在一个List<ProductVo>中。
在service层进行调用得到这个list集合,一般我们都是通过for循环或者迭代器进行遍历,做判断,现在java8新特性Stream能帮我们简洁且高效的编码完成该循环。不需要再写冗杂沉重的循环了
代码如下:
//调用dao层方法,得到将产量分组好的集合数据 List<ProductVO > list= productDao.getProduct();
//通过stream流 将月份等于5的元素取出来,findFirst取第一个元素 ProductVO vo =
list.stream().filter(f->Integer.parseInt(f.getMonth())=5).findFirst().get();
Stream的findFirst方法在此流中查找第一个元素作为Optional。 get方法则返回处理的元素。
如果findFirst选择的元素为null,它将抛出NullPointerException。
可能会遇到的问题:
NoSuchElementException:空指针的话可以用这个方法进行过滤 orElse方法:
将.get()替换为.orElse(null),这样就会返回null值了。不会再报错