0

In the following piece of code, I am saving firstname and emailId of a person in a hashmap.I wish to print the firstname of the entries that have emailId ending with 'gmail.com' in ascending order. for that I have used TreeMap class of java.

but the problem is printing the keys where emailId pattern matches..

public class RegExSolution {

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int N = in.nextInt();
    Map<String, String> emailDetail = new HashMap<>();
    for (int a0 = 0; a0 < N; a0++) {
        String firstName = in.next();
        String emailID = in.next();
        emailDetail.put(firstName, emailID);
    }
    Map<String, String> emailDetailTree = new TreeMap<>(emailDetail);

    Iterator i = emailDetailTree.entrySet().iterator();
    while (i.hasNext()) {
    i.next();
        if (Pattern.matches("[a-z]+@gmail\\.com$", "here I wish to get emaild from entry(i.e value from TreeMap)")) {
            System.out.println("here I wish to print the firstname(i.e. key from TreeMap) ");
        } else {
            continue;
        }
    }
}
}

Thanks in advance.

Namrata Shukla
  • 157
  • 2
  • 8

1 Answers1

2

You're throwing away the results from your iterator. Keep the entry and you can access the key and value for printing:

Iterator<Map.Entry<String, String>> i = emailDetailTree.entrySet().iterator();
while(i.hasNext()) {
    Map.Entry<String, String> entry = i.next();
    ...
Kayaman
  • 72,141
  • 5
  • 83
  • 121