Java Day 28: RegEx, Patterns, and Intro to Databases



Consider a database table, Emails, which has the attributes First Name and Email ID. Given N rows of data simulating the Emails table, print an alphabetically-ordered list of people whose email address ends in @gmail.com.



  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3. import java.util.Scanner;
  4. import java.util.regex.Matcher;
  5. import java.util.regex.Pattern;
  6. public class Solution {
  7. public static void main(String[] args) {
  8. Scanner in = new Scanner(System.in);
  9. int N = in.nextInt();
  10. String emailRegEx = "[email protected]\\.com$";
  11. Pattern pattern = Pattern.compile(emailRegEx);
  12. ArrayList<String> list = new ArrayList<>();
  13. for (int i = 0; i < N; i++) {
  14. String name = in.next();
  15. String email = in.next();
  16. Matcher matcher = pattern.matcher(email);
  17. if (matcher.find()) list.add(name);
  18. }
  19. Collections.sort(list);
  20. list.forEach(System.out::println);
  21. }
  22. }