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

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

问题描述

我是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()));
 }

HANDLE for循环有没有更好的方法?感谢任何帮助。

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

推荐答案

您现在拥有的代码完美无缺,但也是 O (n * m)因为 removeIf 为每个<$ c $迭代 List C>儿童。改进的一种方法是将每个孩子的 personId 存储在 Set< String> 中并删除每个来自列表< Person> ,如果他们的 personId 包含在设置

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天全站免登陆