abdou amer abdou amer - 6 months ago 35
Java Question

Java ObservableList filtering with predicate with Strings

I have an observable list, I tried to filter it by different predicates.

I have nested objects on which I do filtering.

Here is the first pojo

public Class Transaction {
private String name;
private Account account ;
private BigDecimal ammout ;
}


public class Account{
private String nameBank;
private String number;
private BigDecimal balance;
}


I have used Java 8 stream API to do filtering, it doesn't work for String, but it works perfectly for balance and other types.

Here is how i do filter my list:

public void findByBankName(String bankName) {
ObservableList<Transaction> transactionList = FXCollections
.observableArrayList();
return transactionList.stream()
.filter(t ->
t.getAccount().getnameBank().Contains(bankName) )
.collect(Collectors.toList());

// Instead it work when i do
// .filter(t -> t.getAccount().getBalance().doubleValue() > 0 )
}


So, what's the issue with my code ?

Answer

I think you just hand-typed the code in this question, thats why there are compilation errors. I refactored your classes (with some assumptions).

Account class

public class Account{
    private String nameBank;
    private String number;
    private BigDecimal balance;

    public String getNameBank() {
        return nameBank;
    }

    public void setNameBank(String nameBank) {
        this.nameBank = nameBank;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public BigDecimal getBalance() {
        return balance;
    }

    public void setBalance(BigDecimal balance) {
        this.balance = balance;
    }
}

Transaction class

public class Transaction  {
    private String name;
    private Account account ;
    private BigDecimal ammout ;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Account getAccount() {
        return account;
    }

    public void setAccount(Account account) {
        this.account = account;
    }

    public BigDecimal getAmmout() {
        return ammout;
    }

    public void setAmmout(BigDecimal ammout) {
        this.ammout = ammout;
    }
}

I created this class and named as TransactionsManager

public class TransactionsManager {
    private final List<Transaction> transactionsList;

    public TransactionsManager(List<Transaction> transactionsList) {
        this.transactionsList = Collections.unmodifiableList(transactionsList);
    }

    public List<Transaction> findByBankName(String bankName) {
        return transactionsList.stream()
                .filter(t -> t.getAccount().getNameBank().contains(bankName))
                .collect(Collectors.toList());
    }
}

Hopefully, this helps!!