You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java使用TreeMap提取符合邮箱规则的键并升序输出的问题

解决思路与修正代码

嘿,我来帮你搞定这个问题!你想要筛选出所有邮箱以gmail.com结尾的用户名字,并且按升序输出对吧?你用TreeMap来实现排序的思路是对的,但可能在输入处理、筛选条件或者数据迁移的环节出了问题。下面是完整的修正代码,我会一步步给你拆解关键点:

完整修正代码

import java.util.*;

public class RegExSolution {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int N = in.nextInt();
        // 必须处理nextInt()后的换行符,否则后续nextLine()会读取空字符串
        in.nextLine();
        
        Map<String, String> emailDetail = new HashMap<>();
        
        // 读取N组用户数据,存入HashMap
        for (int i = 0; i < N; i++) {
            String[] userInput = in.nextLine().split(" ");
            String firstName = userInput[0];
            String emailId = userInput[1];
            emailDetail.put(firstName, emailId);
        }
        
        // 用TreeMap自动按名字升序排列
        Map<String, String> sortedGmailUsers = new TreeMap<>();
        
        // 遍历HashMap,筛选符合条件的邮箱
        for (Map.Entry<String, String> entry : emailDetail.entrySet()) {
            String email = entry.getValue();
            // 两种筛选方式选一种:
            // 方式1:简单判断结尾(适合确定输入格式规范的情况)
            // if (email.endsWith("gmail.com")) {
            // 方式2:正则匹配,确保邮箱包含@且后缀是gmail.com(更严谨)
            if (email.matches(".*@gmail.com$")) {
                sortedGmailUsers.put(entry.getKey(), email);
            }
        }
        
        // 输出升序排列的名字
        for (String name : sortedGmailUsers.keySet()) {
            System.out.println(name);
        }
        
        in.close();
    }
}

关键问题说明

  • 输入换行处理:nextInt()只会读取数字,不会消耗后面的换行符,如果直接调用nextLine(),第一次会读到空字符串,所以必须加in.nextLine()跳过这个换行。
  • 筛选条件的严谨性:
    • 用endsWith("gmail.com")简单直接,但可能匹配到xxxgmail.com这种不符合邮箱格式的字符串;
    • 用正则.*@gmail.com$可以确保邮箱里存在@符号,且后面紧跟gmail.com结尾,更符合实际邮箱规则。
  • 排序实现:TreeMap会自动按照键的自然顺序(String的字典序)升序排列,所以把符合条件的名字作为键存入TreeMap后,遍历keySet就能直接得到升序结果。
  • 名字重复的场景:如果存在同名用户,TreeMap的键不能重复(后存入的会覆盖前面的),这时候可以改用ArrayList存储符合条件的名字,再调用Collections.sort(gmailNames)来排序,示例代码如下:
List<String> gmailNames = new ArrayList<>();
for (Map.Entry<String, String> entry : emailDetail.entrySet()) {
    if (entry.getValue().matches(".*@gmail.com$")) {
        gmailNames.add(entry.getKey());
    }
}
Collections.sort(gmailNames);
for (String name : gmailNames) {
    System.out.println(name);
}

内容的提问来源于stack exchange,提问作者Namrata Shukla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:20:21