Skip to content

Java Stream filter with regex not working

hope somebody can help me. I have a ArrayList of a Invoice class. What I’m trying to get is to filter this ArrayListand find the first element which one of its properties matches with a regex. The Invoiceclass looks like this:

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

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

   //getters and setters

I’m filtering with this regex (\D+) in order to find if there is any value in the orderNumproperty that hasn’t the format of an integer. So basically I’m using this stream

    Optional<Invoice> invoice = list
                            .filter(line -> line.getOrderNum())

But It doesn’t work. Any idea? I’ve been searching and I found how to use the pattern.asPredicate() like this:

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

List<String> matching =

With List of Integer, String, etc, but I haven’t found how to do it with a POJO. Any help will be much appreciated. Nice day



You’re almost there.

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

What’s happening here is that you create a custom Predicate used to filter the stream. It converts the current Invoice to a boolean result.

If you already have a compiled Pattern that you’d like to re-use:

Pattern p = …
Optional<Invoice> invoice =
  .filter(line -> p.matcher(line.getOrderNum()).matches())