2017-09-20 83 views
1

我有以下代码:自定义功能:适用于流

Function<String,Boolean> funcParse = (String f)-> { 
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(f); 
    try 
    { 
     YearMonth.parse(date , formatter); 
    } 
    catch (DateTimeParseException e) 
    { 
     return false; 
    } 
    return true; 
}; 

Arrays.stream(MONTHYEAR_FORMATS.split("\\|")).findFirst(format -> funcParse.apply(format)); 

我在这里的语法警告:apply (java.lang.String) in Function cannot be applied to (<lambda parameter>)什么我做错了什么?

+2

'的FindFirst()'不带任何参数。你可以使用'.filter(..)。findFirst()',并且让'funcParse'成为'Predicate '。 –

+3

但是,首先创建一个'Function '而不是创建'Predicate '的意义在哪里呢? – Holger

+0

谢谢,我同意 –

回答

1

这实际上是为Bindable一个很好的候选人(我认为我已经看到了这个,因为一些霍尔格的答案,但现在不能找到它)。 所以,你有你平时的解析方法:

static boolean parse(String date, String format) { 
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format); 
    try { 
     YearMonth.parse(date, formatter); 
    } catch (DateTimeParseException e) { 
     return false; 
    } 
    return true; 
} 

与您共创bindValue方法:

public static <T, U> Predicate<U> bindValue(BiFunction<T, U, Boolean> f, T t) { 
    return u -> f.apply(t, u); 
} 

基本上结合datePredicate - 因为date不会改变,只有format一样。

然后

BiFunction<String, String, Boolean> toPredicate = Bindable::parse; 
Predicate<String> predicate = bindValue(toPredicate, date); 

使用情况,这很简单:

String date = "SomeDate"; 
Predicate<String> predicate = bindValue(toPredicate, date); 
Arrays.stream(MONTHYEAR_FORMATS.split("|")) 
     .filter(predicate) 
     .findFirst();