我有以下代码:
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>)
我究竟做错了什么?
最佳答案
这实际上是Bindable
的一个很好的候选者(我认为我已经将其视为Holger的一些答案,但现在找不到)。
这样你就有了常用的解析方法:
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);
}
基本上将日期
绑定(bind)到谓词
- 因为日期
不会改变,只有格式
会改变。
然后
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();
关于java - 自定义函数: apply in Stream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46325741/