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

Java中如何查找List列表中包含匹配字符串的元素的索引

实现方案

核心逻辑为自行遍历List的每个元素,逐个判断元素是否包含目标子串,同时记录对应索引即可,以下提供两种常用实现方式:

1. 普通for循环实现(兼容所有Java版本)

查找第一个匹配的索引

int targetIndex = -1;
String keyword = "address";
for (int i = 0; i < student.size(); i++) {
    if (student.get(i).contains(keyword)) {
        targetIndex = i;
        break; // 找到第一个匹配项后终止遍历,需要全量查找可删除该行
    }
}
// 遍历结束后targetIndex为-1代表无匹配项,否则为第一个匹配元素的索引

查找所有匹配的索引

List<Integer> matchIndexes = new ArrayList<>();
String keyword = "address";
for (int i = 0; i < student.size(); i++) {
    if (student.get(i).contains(keyword)) {
        matchIndexes.add(i);
    }
}

2. Stream实现(Java 8及以上版本适用,写法更简洁)

查找第一个匹配的索引

String keyword = "address";
OptionalInt firstMatchIndex = IntStream.range(0, student.size())
        .filter(i -> student.get(i).contains(keyword))
        .findFirst();

if (firstMatchIndex.isPresent()) {
    System.out.println("匹配索引:" + firstMatchIndex.getAsInt());
} else {
    System.out.println("无匹配元素");
}

查找所有匹配的索引

String keyword = "address";
List<Integer> matchIndexes = IntStream.range(0, student.size())
        .filter(i -> student.get(i).contains(keyword))
        .boxed()
        .collect(Collectors.toList());

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 07:48:02