使用流将模式列表转换为谓词

Convert a list of Patterns into Predicates using stream

我正在尝试将模式列表(其类型为 string)转换为谓词,但由于某些原因,我的大脑总是以接近以下代码的方式结束:

    List<Predicate> predicates = patterns.stream()
        .map(Pattern::asPredicate)
        .collect(Collectors.toList());

这显然无法编译。编写转换流的最佳方式是什么?

这是我收到的错误消息:

Provider.java:32: error: method map in interface Stream<T> cannot be applied to given types;
            .map(Pattern::asPredicate)
            ^
  required: Function<? super String,? extends R>
  found: Pattern::a[...]icate
  reason: cannot infer type-variable(s) R
    (argument mismatch; invalid method reference
      method asPredicate in class Pattern cannot be applied to given types
        required: no arguments
        found: String
        reason: actual and formal argument lists differ in length)
  where R,T are type-variables:
    R extends Object declared in method <R>map(Function<? super T,? extends R>)
    T extends Object declared in interface Stream
MsisdnPartitioningProvider.java:32: error: invalid method reference
            .map(Pattern::asPredicate)
                 ^
  non-static method asPredicate() cannot be referenced from a static context
Note: MsisdnPartitioningProvider.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
2 errors

您提到 patterns 是字符串,即它可能是 List<String>,因此您可能想尝试以下操作:

List<Predicate> predicates = patterns.stream().map(Pattern::compile).map(Pattern::asPredicate)
                .collect(Collectors.toList());

注意:您可以使用 List<Predicate<String>> 来避免 raw type 用户@MC Emperor 提到的警告