alex safsafsd
alex safsafsd

Reputation: 161

How can I get data from request where parameters is regex?

Sorry for my English. I need to filter List<Contact> by name using regex and get new List<Contact> where name matches regex. Contact has two fields name and id.

For example

^B.*$ - returns contacts that do NOT start with B

Maybe something like this, but I do not know how to do it by choosing a name and comparing with regex.

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

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

How can i do this?

Upvotes: 2

Views: 104

Answers (1)

holi-java
holi-java

Reputation: 30696

you can filtering List<Contact> by its name. for example:

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

List<Contact> matched = list.stream()
  .filter(it -> it!=null && it.getName()!=null && pattern.matcher(it.getName()).matches())
  .collect(Collectors.toList());

OR using filter chain to make the code more expressive, for example:

List<Contact> matched = list.stream()
                            .filter(Objects::nonNull)
                            .filter(it -> it.getName() != null)
                            .filter(it -> pattern.matcher(it.getName()).matches())
                            .collect(Collectors.toList());

Upvotes: 3

Related Questions