tupac shakur
tupac shakur

Reputation: 678

How to use stream on method that return boolean value with condition

I am using this method:

public boolean checkRowsFilterNameBy(String filter){
    waitForElmContainsText(searchButton, "Search");
    List<AuditRow> listRows = auditTable.getTable();
    for(AuditRow row : listRows){
        if(!row.nameStr.equals(filter)||!row.nameStr.contains(filter))
            return false;
    }
    return true;
}

and I want to be able to change it using Stream , I've tried the following, but I am missing something:

listRows.stream().forEach(auditRow -> {
           if(auditRow.actionStr.equals(filter))return true;} else return false;);

but I am getting an error.

Upvotes: 8

Views: 34413

Answers (4)

Gustavo Marquez
Gustavo Marquez

Reputation: 499

This work for me, if any of the conditions become true

return listRows.stream().anyMatch(row -> !row.nameStr.equals(filter) || !row.nameStr.contains(filter)) // boolean;

Upvotes: 0

Ravindra Ranwala
Ravindra Ranwala

Reputation: 21124

You may do it like so,

listRows.stream().allMatch(row -> row.nameStr.equals(filter) && row.nameStr.contains(filter));

Update

As per Holgers suggestion, this can be further simplified as this.

listRows.stream().allMatch(row -> row.nameStr.contains(filter));

The use of equals or contains may vary depending on your context.

Upvotes: 9

Naman
Naman

Reputation: 31888

Getting rid of all the negations using de-morgan's law such that

(!a || !b) => !(a && b)

you can use allMatch as:

return listRows.stream()
        .allMatch(row -> row.nameStr.equals(filter)
                && row.nameStr.contains(filter));

which has a similar version using noneMatch :

return listRows.stream()
        .noneMatch(row -> (!row.nameStr.equals(filter) 
                || !row.nameStr.contains(filter)));

A logical improvement in your code could further be to just check for contains which would imply equality as well, this would cut down to:

return listRows.stream().allMatch(row -> row.nameStr.contains(filter));

Upvotes: 0

MWB
MWB

Reputation: 1879

I would use a stream filter to filter out all elements that are true and do a count on the result.

boolean result = (listRows.stream().filter(row -> row.nameStr.equals(filter) && row.nameStr.contains(filter)).count() == 0);

Upvotes: 0

Related Questions