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
相关产品推荐
相关产品推荐

