extracting keys from treemap object [duplicate]

ε祈祈猫儿з 提交于 2019-12-24 19:43:17

问题


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.


回答1:


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();
    ...


来源:https://stackoverflow.com/questions/49686186/extracting-keys-from-treemap-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!