Remove certain elements in one list based on condition from another list(根据条件从另一个列表中删除一个列表中的某些元素)
问题描述
我对 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 遍历每个 Children 的 List.一种改进方法是将每个孩子的 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()));
这篇关于根据条件从另一个列表中删除一个列表中的某些元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:根据条件从另一个列表中删除一个列表中的某些
基础教程推荐
- 大摇大摆的枚举 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
