Search code examples
javaspring-bootjava-8spring-dataspring-data-jpa

use of removeif for filtering list containing objects


I am stuck on using removeif java 8 and looking for some help

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

from transactions I want to remove those transactions based on checking property of object

if transaction.getFileHash is not null then I want to remove that transaction. if transaction.getFileHash is null I want to keep it.

so I am trying removeif

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

but I am getting errors. Is someone can explain how removeif work with object properties?


Solution

  • You can retrieve the list and then remove the elements with removeIf:

    List<ACHTransaction> transactions =
        transactionDao.retrieveTransactions(getJobParameters());
    
    transactions.removeIf(t -> t.getFileHash() != null);
    

    Or you can do as in your own answer and use a stream:

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