【问题标题】:Custom Function: apply in Stream自定义函数:在 Stream 中应用
【发布时间】:2017-09-20 15:10:45
【问题描述】:

我有以下代码:

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 (&lt;lambda parameter&gt;) 我做错了什么?

【问题讨论】:

  • findFirst() 不带任何参数。您可以使用.filter(..).findFirst(),并让funcParse 成为Predicate&lt;String&gt;。
  • 但是首先创建Function&lt;String,Boolean&gt; 而不是创建Predicate&lt;String&gt; 有什么意义呢?

标签: java function lambda java-8 java-stream


【解决方案1】:

这实际上是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);
}

基本上将date 绑定到Predicate - 因为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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-30
    • 2021-06-07
    • 2020-02-10
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多