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

如何判断ArrayList中的元素是否包含指定子字符串?

解决ArrayList元素包含指定子串/字符组合的问题

嘿,我明白你的需求啦——你现在用words.contains("Axe")是在检查列表里有没有完全等于"Axe"的元素,但你实际想找的是列表中是否存在某个元素内部包含"Axe"这个子串,对吧?下面给你几种实用的实现方式,还能拓展到更复杂的字符组合检查:

方法1:循环遍历(最直观易理解)

直接逐个遍历ArrayList里的元素,用String.contains()方法判断每个元素是否包含目标子串:

ArrayList<String> words = new ArrayList<String>();
words.add("Wooden Axe");
words.add("Stone Axe");

boolean hasAxeElement = false;
// 增强for循环遍历每个元素
for (String word : words) {
    if (word.contains("Axe")) {
        hasAxeElement = true;
        break; // 找到匹配项就停止遍历,提升效率
    }
}

if (hasAxeElement) {
    System.out.println("列表里存在包含'Axe'的元素!");
    // 这里编写你需要执行的逻辑
} else {
    System.out.println("未找到包含'Axe'的元素");
}

方法2:Java 8+ Stream API(更简洁优雅)

如果你的项目使用Java 8及以上版本,Stream API可以让代码更紧凑:

ArrayList<String> words = new ArrayList<String>();
words.add("Wooden Axe");
words.add("Stone Axe");

// anyMatch()会遍历元素,只要有一个满足条件就返回true
boolean hasAxeElement = words.stream().anyMatch(word -> word.contains("Axe"));

if (hasAxeElement) {
    // 执行你的业务逻辑
    System.out.println("找到了包含'Axe'的元素");
}

拓展:检查特定字符组合(正则表达式匹配)

如果你的需求不是简单的子串匹配,而是更复杂的字符组合(比如元素以"Axe"结尾、包含"Axe"且前面是大写字母等),可以用正则表达式配合String.matches():
比如检查元素是否以"Axe"结尾:

boolean endsWithAxe = words.stream().anyMatch(word -> word.matches(".*Axe$"));

这里的.*Axe$是正则表达式:.*表示任意数量的任意字符,$表示字符串结尾,完美匹配以"Axe"收尾的元素。

额外小技巧:获取所有匹配的元素

如果你不仅要判断是否存在,还想拿到所有包含目标子串的元素,可以用filter()配合collect():

import java.util.stream.Collectors;

// 收集所有包含"Axe"的元素到新列表
List<String> axeRelatedWords = words.stream()
    .filter(word -> word.contains("Axe"))
    .collect(Collectors.toList());

// 遍历输出结果
axeRelatedWords.forEach(System.out::println);
// 会输出:Wooden Axe、Stone Axe

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.01 03:12:48