Java流过滤器与正则表达式无法正常工作

pbu*_*gov 2 java regex pojo java-8 java-stream

希望有人能帮助我.我有ArrayListInvoice堂课.我想要得到的是过滤这个ArrayList并找到其中一个属性与a匹配的第一个元素regex.这个Invoice类看起来像这样:

public class Invoice {
   private final SimpleStringProperty docNum;
   private final SimpleStringProperty orderNum;

   public Invoice{
    this.docNum = new SimpleStringProperty();
    this.orderNum = new SimpleStringProperty(); 
}   

   //getters and setters
}
Run Code Online (Sandbox Code Playgroud)

我正在使用它regex (\\D+)进行过滤,以便查找orderNum属性中是否存在任何不具有整数格式的值.所以基本上我正在使用这个流

    Optional<Invoice> invoice = list
                            .stream()
                            .filter(line -> line.getOrderNum())
                            .matches("(\\D+)"))
                            .findFirst();
Run Code Online (Sandbox Code Playgroud)

但它不起作用.任何的想法?我一直在寻找,我发现如何使用pattern.asPredicate()这样:

Pattern pattern = Pattern.compile("...");

List<String> matching = list.stream()
        .filter(pattern.asPredicate())
        .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

随着ListInteger,String等等,但我还没有找到如何与做POJO.任何帮助都感激不尽.美好的一天

jen*_*ram 6

你快到了.

Optional<Invoice> invoice = list.stream()
  .filter(invoice -> invoice.getOrderNum().matches("\\D+"))
  .findFirst();
Run Code Online (Sandbox Code Playgroud)

这里发生的是您创建Predicate用于filter流的自定义.它将当前Invoice转换为布尔结果.


如果您已经有一个Pattern您想要重新使用的编译:

Pattern p = …
Optional<Invoice> invoice = list.stream()
  .filter(invoice -> p.matcher(invoice.getOrderNum()).matches())
  .findFirst();
Run Code Online (Sandbox Code Playgroud)