3
我在數字List
以驗證沒有負數的方法:參考(在一個lambda使用)的方法與指定的參數
private void validateNoNegatives(List<String> numbers) {
List<String> negatives = numbers.stream().filter(x->x.startsWith("-")).collect(Collectors.toList());
if (!negatives.isEmpty()) {
throw new RuntimeException("negative values found " + negatives);
}
}
是否有可能使用一種方法的參考,而不是x->x.startsWith("-")
?我想過String::startsWith("-")
,但沒有工作。
我懷疑是否有可能得到一個「應用」方法的引用,但你可以創建lambda之前,只提供它作爲參數。 – user2864740
不是你問的問題,但你可以使用'noneMatch'更簡單地做這個測試。例如,'numbers.stream()。noneMatch(x - > x.startsWith(「 - 」));' –