2017-09-07 30 views
2

希望有人可以幫助我。我有一個Invoice類的ArrayList。我試圖得到的是過濾這個ArrayList,並找到其中一個屬性匹配regex的第一個元素。 的Invoice類看起來是這樣的:與正則表達式不工作的Java流過濾器

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

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

    //getters and setters 
} 

我這個regex(\\D+)爲了篩選發現,如果在有不是整數的格式orderNum屬性的任何值。 所以基本上我使用這個流

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

但它不起作用。任何想法? 我一直在尋找,我發現瞭如何使用pattern.asPredicate()this

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

List<String> matching = list.stream() 
     .filter(pattern.asPredicate()) 
     .collect(Collectors.toList()); 

隨着IntegerListString等,但我還沒有找到如何與POJO做到這一點。 任何幫助將不勝感激。 美好的一天

+0

java8流沒有'matches'方法,是該代碼有效? – ByeBye

回答

6

你快到了。

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

這裏發生的事情是,你創建一個用來filter流自定義Predicate。它將當前的Invoice轉換爲布爾結果。


如果你已經有了一個編譯Pattern,你想重新使用:

Pattern p = … 
Optional<Invoice> invoice = list.stream() 
    .filter(invoice -> p.matcher(invoice.getOrderNum()).matches()) 
    .findFirst(); 
+0

謝謝,它工作得很好。 – pburgov