I was reading a not related thread , when I read a comment: Any time I find myself needing a multi-line lambda, I move the lines to a private method and pass the method reference instead of the lambda.
I was asking: which is the correct way to implement this behaviour? With a boolean method as posted in comment, or with predicate?
Example:
let's say I wanna check if a Table
is usable, where usable means isClean
, isEmpty
, hasChair
.
class Table{
public boolean hasChair(){...}
public boolean isClean(){...}
public boolean isEmpty(){...}
}
I can implement my filtering test for my list List<Table> tablesList = Arrays.asList(table1,table2,table3,table4);
in 2 ways: the first with boolean:
public boolean isUsable(){
return hasChair() && isClean() && isEmpty();
}
And use it with tablesList.stream().filter(Table::isUsable)
The second way is with predicate:
public Predicate<Table> isUsable(){
return table -> table.isEmpty() && table.isClean() && table.hasChair();
}
Usable with tablesList.stream().filter(isUsable())
Which is the correct implementation? Why choose one instead of other? Is there any big difference?