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

谁说胖子不能爱 提交于 2020-12-08 06:46:40

问题


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 equality 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!