使用removeif过滤包含对象的列表

4

我在使用Java 8中的removeIf遇到了困难,希望能得到一些帮助。

List<ACHTransaction> transactions = transactionDao.retrieveTransactions(getJobParameters();

我希望能够根据对象的检查属性从交易中删除这些交易,涉及到it技术相关内容。

如果transaction.getFileHash不为空,则我想要删除该交易。 如果transaction.getFileHash为空,则我想要保留它。

因此,我尝试使用removeif方法进行删除操作。

List<ACHTransaction> transactions = transactionDao.retrieveTransactions(getJobParameters().removeIf(t -> (Optional.ofNullable(t.getFileHash()).orElse(0).intValue() != 0));

但我遇到了错误。有人能解释一下如何使用 removeif 和对象属性吗?


1
你遇到了什么错误? - Mureinik
不兼容的类型:需要 ACHTransaction,但找到了 boolean。 - Satya
4
removeIf方法对调用它的集合进行修改,并返回一个布尔值,告诉你它是否修改了集合,也就是是否有任何匹配的元素被删除。你不能将该布尔值赋值给列表。 - Holger
4个回答

6
您可以检索列表,然后使用removeIf删除元素:
List<ACHTransaction> transactions =
    transactionDao.retrieveTransactions(getJobParameters());

transactions.removeIf(t -> t.getFileHash() != null);

或者你可以像你自己的答案一样使用流:

List<ACHTransaction> transactions =
    transactionDao.retrieveTransactions(getJobParameters()).stream()
        .filter(t -> t.getFileHash() == null)
        .collect(Collectors.toList());

t是可空的,这就是我使用optional的原因。 - Satya
@Satya 是的,t 可为空,但这并不意味着在看到 null 值时必须使用 Optional。您应该尽量编写易于阅读和理解的代码。Optional 应该被用作方法返回类型。 - fps
是的,你说得对。在我的情况下,我没有拥有其他代码来纠正设计问题。感谢您的评论。 - Satya

1

我测试了下面的代码,它按照要求工作。我希望这就是你要找的。

import java.util.ArrayList;
import java.util.List;

public class TestRemoveIf {



public static void main(String[] args) {

    Transaction myTrans1 = new Transaction("myTrans1");
    Transaction myTrans2 = new Transaction("myTrans2");
    Transaction myTrans3 = new Transaction("myTrans3");
    Transaction myTrans4 = new Transaction("myTrans4");

    myTrans1.setFileHash("not Null");
    myTrans3.setFileHash("not null");

    List<Transaction> trList = new ArrayList();
    trList.add(myTrans1);
    trList.add(myTrans2);
    trList.add(myTrans3);
    trList.add(myTrans4);

    trList.removeIf(t -> t.getFileHash()!=null);

    System.out.println(trList);


}


}


public class Transaction {

String fileHash;
String name;

public String getFileHash() {
    return fileHash;
}

public void setFileHash(String fileHash) {
    this.fileHash = fileHash;
}

public Transaction(String name) {
    super();
    this.name = name;
}

@Override
public String toString() {
    return "Transaction [fileHash=" + fileHash + ", name=" + name + "]";
}



}

-1
目前我是这样解决的
List<ACHTransaction> transactions =
        achManagementDao
            .retrieveTransactions(getJobParameters())
            .stream()
            .filter(t -> !(Optional.ofNullable(t.getFileHash()).orElse(0).intValue() == 0))
            .collect(Collectors.toList());

但如果有更好的方法,请告诉我


2
filter操作中使用Optional毫无意义。这远非可读代码,而且那些需要维护它的人将会很难理解你的意图。最好还是直接使用filter(t -> t.getFileHash() == null) - fps

-1
List<ACHTransaction> transactions =
    transactionDao.retrieveTransactions(getJobParameters());

Predicate<ACHTransaction> cond = (t -> Objects.nonNull(t.getFileHash())));

transactions.removeIf(cond);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接