2

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

1
  • java8 stream has no matches method, is this code valid? Commented Sep 7, 2017 at 7:15

1 Answer 1

9

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.