Tuesday 26 December 2017

How to filter list of email addresses using asPredicate method of Pattern class | Regex in java


Click here to watch on Youtube : 
https://www.youtube.com/watch?v=mFNZpvYVTkU&list=UUhwKlOVR041tngjerWxVccw

RegexPredicateDemo.java

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class RegexPredicateDemo
{

    public static void main(String[] args)
    {
        String regex = "^(.+)@gmail.com$";
        Pattern pattern = Pattern.compile(regex);

        /*
         * Returns:The predicate which can be used for matching on a
         * string
         */

        Predicate<String> emailFilterPredicate = pattern.asPredicate();

        List<String> emailList = Arrays.asList("peter@yahoo.com",
                "bob@gmail.com", "juli@gmail.com",
                "david@rediff.com");

        /*
         *  Apply predicate filter
         */

        List<String> desiredEmailList = emailList.stream()
                                           .filter(emailFilterPredicate)
                                           .collect(Collectors.<String>toList());

        desiredEmailList.forEach(System.out::println);
    }

}

Output

bob@gmail.com
juli@gmail.com

RegexDemo.java

import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexDemo
{

    public static void main(String[] args)
    {

        String regex = "^(.+)@gmail.com$";
        Pattern pattern = Pattern.compile(regex);

        List<String> emailList = Arrays.asList("peter@yahoo.com",
                "bob@gmail.com", "juli@gmail.com",
                "david@rediff.com");

        for (String email : emailList)
        {
            Matcher matcher = pattern.matcher(email);

            if (matcher.matches())
            {
                System.out.println(email);
            }
        }
    }

}

Output

bob@gmail.com
juli@gmail.com

Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/RegexDemo_asPredicate.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/RegexDemo_asPredicate

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/57d5e7f2c5fabff367c40b36a92925e1158e7f5a/BasicJava/RegexDemo_asPredicate/?at=master

See also:
  • All JavaEE Videos Playlist
  • All JavaEE Videos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • No comments:

    Post a Comment