简体   繁体   English

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

[英]Remove certain elements in one list based on condition from another list

I'm fairly new to Java8.我是 Java8 的新手。 I have a requirement to subtract/remove POJOs in one list based on certain criteria (from another list) and show it on UI.我需要根据特定条件(从另一个列表)减去/删除一个列表中的 POJO,并将其显示在 UI 上。

Iterate one list and search for condition Remove the object Send the original list to UI迭代一个列表并搜索条件 移除对象 将原始列表发送到 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.

..MAIN CODE.. ..主要代码..

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

Is there any BETTER way to HANDLE for-loop?有没有更好的方法来处理 for 循环? Any help is appreciated.任何帮助表示赞赏。

The code that you have right now works perfectly, but is also O(n * m) since removeIf iterates through the List for every Children .您现在拥有的代码可以完美运行,但也是O(n * m)因为removeIf遍历每个ChildrenList 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 :一种改进方法是将每个孩子的personId存储在Set<String>中,如果personId包含在Set中,则从List<Person> Person删除每个人:

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

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

Just another way of doing same but without mutating the original list:只是另一种做同样但不改变原始列表的方法:

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

        personList = personList.stream().filter(person ->
                !childIds.contains(person.getPersonId())
        ).collect(Collectors.toList());

It should have a bit of increased space complexity but you could take advantage of parallelStream here.它应该会增加一些空间复杂性,但您可以在这里利用parallelStream

Adding this here in case someone needs it;在这里添加这个以防有人需要它;

If what you want to do is not checking the contents, but an equalization, you can do the same code as follows;如果你想做的不是检查内容,而是均衡,你可以做同样的代码如下;

listName.removeIf(listItem -> listItem.getName().equalsIgnoreCase("Name") ||
                    listItem.getName().equalsIgnoreCase("Other Name"));

This code is versatile and saved me lines of code and the need for a forEach loop.这段代码用途广泛,节省了我的代码行和 forEach 循环的需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM