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

如何高效替换邮箱列表中指定字符并返回完整列表?

高效替换邮箱列表中的指定字符并返回完整列表

你需要遍历邮箱列表,替换掉任意位置的指定字符(此处为+)后返回完整列表。当前代码虽能实现需求,但可以简化为更高效的版本——不需要分两次处理含+和不含+的邮箱,因为String.replaceAll()方法在目标字符不存在时会直接返回原字符串,一次流操作就能完成所有处理:

List<String> emailList = new ArrayList<>();
emailList.addAll(Arrays.asList("testEmail@gmail.com","TestnewEmail+454332@gmail.com","testgmail+4342232545@gmail.com"));

List<String> updatedEmail = emailList.stream()
        .map(email -> email.replaceAll("\\+", ""))
        .collect(Collectors.toList());

updatedEmail.forEach(email -> System.out.println("email: " + email));

优化说明:

  • 无需拆分两次过滤与集合操作,一次遍历完成所有替换,减少了额外的集合修改开销
  • 代码逻辑更统一,简洁易读

运行后控制台输出与原代码结果完全一致:

email: testEmail@gmail.com
email: TestnewEmail454332@gmail.com
email: testgmail4342232545@gmail.com

如果需要适配不同的指定字符,可以将目标字符抽为变量(注意正则特殊字符需转义),比如:

String targetChar = "+";
// 替换时处理转义
.map(email -> email.replaceAll("\\" + targetChar, ""))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 04:33:36