根据条件从另一个列表中删除一个列表中的某些元素 [英] Remove certain elements in one list based on condition from another list

查看:40
本文介绍了根据条件从另一个列表中删除一个列表中的某些元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Java8 还很陌生.我需要根据特定条件(从另一个列表中)减去/删除一个列表中的 POJO 并将其显示在 UI 上.

I'm fairly new to Java8. I have a requirement to subtract/remove POJOs in one list based on certain criteria (from another list) and show it on UI.

迭代一个列表并搜索条件移除对象将原始列表发送到 UI

Iterate one list and search for condition Remove the object Send the original list to UI

Children.java
private String firstName;
private String lastName;
private String school;
private String personId;
// Setters and getters.

Person.java
private String personId;
private String fullName;
private String address;
// Setters and Getters.

..主要代码..

  // populated by other methods.
  List<Person> personList;

 //Connect to DB and get ChildrenList
 List<Children> childrenList = criteria.list();

 for(Children child : childrenList) {
    personList.removeIf(person -> child.getPersonId().equals(person.getPersonId()));
 }

有没有更好的方法来处理 for 循环?任何帮助表示赞赏.

Is there any BETTER way to HANDLE for-loop? Any help is appreciated.

推荐答案

您现在拥有的代码运行良好,但也是 O(n * m),因为 removeIf 遍历每个 ChildrenList.一种改进方法是将每个孩子的 personId 存储在 Set 中,并从 List 中删除每个 Person; 如果他们的 personId 包含在 Set 中:

The code that you have right now works perfectly, but is also O(n * m) since removeIf iterates through the List for every Children. One way to improve would be to store every child's personId in a Set<String> and remove every Person from the List<Person> if their personId is contained in the Set:

Set<String> childIds = childrenList.stream()
                                   .map(Children::getPersonId)
                                   .collect(Collectors.toSet());

personList.removeIf(person -> childIds.contains(person.getPersonId()));

这篇关于根据条件从另一个列表中删除一个列表中的某些元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆