【问题标题】:extracting keys from treemap object [duplicate]从树形图对象中提取键[重复]
【发布时间】:2018-09-16 02:12:36
【问题描述】:

在下面的代码中,我将一个人的名字和 emailId 保存在 hashmap 中。我希望按升序打印 emailId 以“gmail.com”结尾的条目的名字。为此,我使用了 java 的 TreeMap 类。

但问题是打印 emailId 模式匹配的键..

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;
        }
    }
}
}

提前致谢。

【问题讨论】:

    标签: java hashmap


    【解决方案1】:

    您正在丢弃迭代器的结果。保留该条目,您可以访问打印的键和值:

    Iterator<Map.Entry<String, String>> i = emailDetailTree.entrySet().iterator();
    while(i.hasNext()) {
        Map.Entry<String, String> entry = i.next();
        ...
    

    【讨论】:

    • 虽然这是一个流解决方案的尖叫。
    • 在开始使用流之前了解迭代器的工作原理不会有什么坏处。
    • 这工作..谢谢。我是 Collections 新手,我从来不知道迭代器可以这样制作。
    • @Kayaman 真的。我只是痒。
    猜你喜欢
    • 1970-01-01
    • 2016-05-25
    • 1970-01-01
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    • 2019-05-17
    • 1970-01-01
    • 2022-01-05
    相关资源
    最近更新 更多