问题
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.
回答1:
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.
回答2:
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 equal
ity as well, this would cut down to:
return listRows.stream().allMatch(row -> row.nameStr.contains(filter));
回答3:
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);
来源:https://stackoverflow.com/questions/54771478/how-to-use-stream-on-method-that-return-boolean-value-with-condition