3 回答

TA貢獻1784條經驗 獲得超2個贊
我想你的意思是第二個例子
public static Predicate<Table> isUsable(){
return table -> table.isEmpty() && table.isClean() && table.hasChair();
}
這可能已經表明這種形式可能會使讀者感到困惑。沒有static你可以寫table.isUsable(),Table::isUsable但它不會按照你的想法去做。
哪個是正確的實現?
我更喜歡 ,Table::isUsable因為它也可以用作table.isUsable實例。
為什么選擇一個而不是另一個?
我覺得第一個例子更自然,更容易混淆。
第二種形式對于操作謂詞更有用,例如 Predicate.or(Predicate)
有什么大的區別嗎?
在這種情況下,使用 Stream 可能會更慢,但更重要的是,更容易混淆。
返回 Predicate 的方法的一個優點是它可以添加到任何類中,例如由于某種原因您不能更改 Table。

TA貢獻1878條經驗 獲得超4個贊
有Predicate<Table> isUsable()
假定你總是需要在需要的地方使用的是邏輯Predicate<Table>
實例,這是一個限制。
另一方面, haveboolean isUsable()
使您可以靈活地Table::isUsable
在Predicate<Table>
需要a的地方使用,或Table::isUsable
用作其他一些功能接口的實現(與該方法的簽名匹配)或直接調用t.isUsable()
特定Table
實例。因此我發現這個替代方案更有用。

TA貢獻1843條經驗 獲得超7個贊
static List<Predicate<Table>> predicateList = Arrays.asList(Table::hasChair, Table::isClean);
static boolean isUsable(Table table) {
return predicateList.stream().allMatch(p -> p.test(table));
}
使用 isUsable:
List<Table> tablesList = ...
Stream<Table> usableTables = tablesList.stream().filter(Table::isUsable);
添加回答
舉報