【问题标题】:Create custom Predicate with Set<String> and String as parameter使用 Set<String> 和 String 作为参数创建自定义谓词
【发布时间】:2019-01-04 14:05:15
【问题描述】:

我有一个 String 作为 "ishant" 和一个 Set&lt;String&gt; 作为 ["Ishant", "Gaurav", "sdnj"] 。我需要为此编写谓词。我试过下面的代码,但它不起作用

Predicate<Set<String>,String> checkIfCurrencyPresent = (currencyList,currency) -> currencyList.contains(currency);

如何创建一个Predicate,它将Set&lt;String&gt;String 作为参数并给出结果?

【问题讨论】:

    标签: java java-8 predicate functional-interface


    【解决方案1】:

    您当前使用的Predicate&lt;T&gt; 表示一个参数的谓词(布尔值函数)

    您正在寻找一个BiPredicate&lt;T,U&gt;,它本质上代表一个两个参数的谓词(布尔值函数)。

    BiPredicate<Set<String>,String>  checkIfCurrencyPresent = (set,currency) -> set.contains(currency);
    

    或带有方法参考:

    BiPredicate<Set<String>,String> checkIfCurrencyPresent = Set::contains;
    

    【讨论】:

    • 如何在代码中调用这个谓词?我正在使用此代码 boolean isCurrencyCodeValid = requestCurrencyCodes.stream() .noneMatch(checkIfCurrencyPresent(currencyValues,requireCurrency));
    【解决方案2】:

    如果您坚持使用Predicate,请使用类似于:

    Set<String> currencies = Set.of("Ishant", "Gaurav", "sdnj");
    String input = "ishant";
    Predicate<String> predicate = currencies::contains;
    System.out.print(predicate.test(input)); // prints false
    

    BiPredicatePredicate 之间的主要区别在于它们的test 方法实现。 Predicate 会使用

    public boolean test(String o) {
        return currencies.contains(o);
    }
    

    BiPredicate 将改为使用

    public boolean test(Set<String> set, String currency) {
        return set.contains(currency);
    }
    

    【讨论】:

      【解决方案3】:

      青峰的回答是完整的。使用BiFunction&lt;T, U, R&gt; 是另一种方式:

      BiFunction<Set<String>,String,Boolean> checkIfCurrencyPresent = Set::contains;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-12-29
        • 1970-01-01
        • 1970-01-01
        • 2021-07-28
        • 1970-01-01
        • 2018-10-31
        • 1970-01-01
        • 2015-03-07
        相关资源
        最近更新 更多