2014-07-22 26 views
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("-"),但沒有工作。

+0

我懷疑是否有可能得到一個「應用」方法的引用,但你可以創建lambda之前,只提供它作爲參數。 – user2864740

+1

不是你問的問題,但你可以使用'noneMatch'更簡單地做這個測試。例如,'numbers.stream()。noneMatch(x - > x.startsWith(「 - 」));' –

回答

7

不,你不能因爲你需要提供一個參數中使用的方法引用,因爲startsWith方法不接受你想謂詞值。你可以寫你自己的方法,如:

private static boolean startsWithDash(String text) { 
    return text.startsWith("-"); 
} 

...然後使用:

.filter(MyType::startsWithDash) 

或者作爲一個非靜態方法,你可以有:

public class StartsWithPredicate { 
    private final String prefix; 

    public StartsWithPredicate(String prefix) { 
     this.prefix = prefix; 
    } 

    public boolean matches(String text) { 
     return text.startsWith(text); 
    } 
} 

然後使用:

// Possibly as a static final field... 
StartsWithPredicate predicate = new StartsWithPredicate("-"); 
// Then... 
List<String> negatives = numbers.stream().filter(predicate::matches)... 

但是那你也不妨製作StartsWithPredicate實施Predicate<String>,只是通過謂詞本身:)