根据条件从另一个列表中删除一个列表中的某些

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 遍历每个 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()));

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How can create a producer using Spring Cloud Kafka Stream 3.1(如何使用Spring Cloud Kafka Stream 3.1创建制片人)
Insert a position in a linked list Java(在链接列表中插入位置Java)
Did I write this constructor properly?(我是否正确地编写了这个构造函数?)
Head value set to null but tail value still gets displayed(Head值设置为空,但仍显示Tail值)
printing nodes from a singly-linked list(打印单链接列表中的节点)
Control namespace prefixes in web services?(控制Web服务中的命名空间前缀?)