首页 > 技术文章 > java8新特性stream流的应用

lu97 2021-05-20 09:08 原文

  在项目的代码编写中遇到这样一个问题。需要对关联方传递过来的列表数据进行一个筛选校验; 把已经回调传递过来的数据给去掉。然后把没有回调过来的数据再接着进行处理。

 

问题大致分析如下:

一个集合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 }

觉得此文不错的,点赞收藏+转发,本人非常感谢!

推荐阅读