java8新特性stream流的应用
2021/5/20 12:29:30
本文主要是介绍java8新特性stream流的应用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
在项目的代码编写中遇到这样一个问题。需要对关联方传递过来的列表数据进行一个筛选校验; 把已经回调传递过来的数据给去掉。然后把没有回调过来的数据再接着进行处理。
问题大致分析如下:
一个集合A包含多个对象,当然这些对象具有相同的属性,另一个集合B包含对象id属性,将A集合对象中存在与B集合对象相同id对象移除。
方法一: 使用递归实现
1 /** 2 * 使用递归方式实现(这个方式消耗性能,不推荐) 3 * @author lyh 4 * @version v-1.0.0 5 * @since 2021/5/20 6 */ 7 public class RecurTest { 8 public static void main(String[] args) { 9 List<Person> listA = new ArrayList<Person>(); 10 //模拟关联方传递过来的数据列表 11 listA.add(new Person("001", "zs", 18)); 12 listA.add(new Person("002", "ls", 19)); 13 listA.add(new Person("003", "wu", 20)); 14 listA.add(new Person("004", "zl", 21)); 15 //模拟在数据库中查询到的数据id列表 16 List<String> listB = new ArrayList<String>(); 17 listB.add("002"); 18 listB.add("004"); 19 //将在数据库中查询存在的数据,根据返回的id列表去移除listA中对应的对象 20 List<Person> listRes = getListRes(listA, listB); 21 System.out.println(listRes); 22 //成功将id为002和004的对象移除:[Person(id=001, name=zs, age=18), Person(id=003, name=wu, age=20)] 23 } 24 25 public static List<Person> getListRes(List<Person> listA, List<String> listB) { 26 for (Person person : listA) { 27 if (listB.contains(person.getId())) { 28 listA.remove(person); 29 //此处使用了递归 30 return getListRes(listA,listB); 31 } 32 } 33 return listA; 34 } 35 }
方法二: 使用stream流实现
1 /** 2 * 使用Stream流方式实现(推荐使用这个方式) 3 * 4 * @author lyh 5 * @version v-1.0.0 6 * @since 2021/5/20 7 */ 8 public class StreamTest { 9 public static void main(String[] args) { 10 List<Person> listA = new ArrayList<Person>(); 11 //模拟关联方传递过来的数据列表 12 listA.add(new Person("001", "zs", 18)); 13 listA.add(new Person("002", "ls", 19)); 14 listA.add(new Person("003", "wu", 20)); 15 listA.add(new Person("004", "zl", 21)); 16 //模拟在数据库中查询到的数据id列表 17 final List<String> listB = new ArrayList<String>(); 18 listB.add("002"); 19 listB.add("004"); 20 //用stream流来处理 21 List<Person> listRes = listA.stream() 22 .filter((Person p) -> listB.contains(p.getId())) 23 .collect(Collectors.toList()); 24 //将要过滤的对象根据id查出来,再利用集合的removeAll方法 25 listA.removeAll(listRes); 26 //查看结果,成功将id为002和004的对象移除:[Person(id=001, name=zs, age=18), Person(id=003, name=wu, age=20)] 27 System.out.println(listA); 28 } 29 }
觉得此文不错的,点赞收藏+转发,本人非常感谢!
这篇关于java8新特性stream流的应用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-05小米13T Pro系统合集:性能与摄影的极致融合,值得你升级的系统ROM
- 2024-10-01基于Python+Vue开发的医院门诊预约挂号系统
- 2024-10-01基于Python+Vue开发的旅游景区管理系统
- 2024-10-01RestfulAPI入门指南:打造简单易懂的API接口
- 2024-10-01初学者指南:了解和使用Server Action
- 2024-10-01Server Component入门指南:搭建与配置详解
- 2024-10-01React 中使用 useRequest 实现数据请求
- 2024-10-01使用 golang 将ETH账户的资产平均分散到其他账户
- 2024-10-01JWT用户校验课程:从入门到实践
- 2024-10-01Server Component课程入门指南