Skip to content
Advertisement

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
                            .stream()
                            .filter(line -> line.getOrderNum())
                            .matches("(\D+)"))
                            .findFirst();

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 = list.stream()
        .filter(pattern.asPredicate())
        .collect(Collectors.toList());

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

Advertisement

Answer

You’re almost there.

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

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 = list.stream()
  .filter(line -> p.matcher(line.getOrderNum()).matches())
  .findFirst();
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement