如何判断嵌套ArrayList中存在指定值并返回外层索引
我来帮你搞定这个问题!你现在的代码确实能输出匹配的字符串,但没法拿到内层列表在外层的索引——因为你直接把外层列表的stream转成了字符串的stream,丢失了索引信息。
这里有两种实用的解决方案,根据你的需求选就行:
1. 找到第一个匹配的索引(最常用场景)
如果只需要第一个包含目标值的内层列表的索引,用IntStream遍历外层列表的索引,然后检查对应位置的内层列表是否包含目标值:
List<List<String>> messages = parseMessages(extract.getPath()); String needle = "test"; // 获取第一个匹配的索引(OptionalInt处理不存在的情况) OptionalInt firstMatchIndex = IntStream.range(0, messages.size()) .filter(index -> messages.get(index).contains(needle)) .findFirst(); // 处理结果 if (firstMatchIndex.isPresent()) { System.out.println("找到匹配的索引:" + firstMatchIndex.getAsInt()); } else { System.out.println("没有找到包含'" + needle + "'的内层列表"); }
2. 获取所有匹配的索引
如果有多个内层列表包含目标值,需要收集所有索引的话,只要把结果收集到List里就行:
import java.util.stream.Collectors; List<List<String>> messages = parseMessages(extract.getPath()); String needle = "test"; List<Integer> allMatchIndices = IntStream.range(0, messages.size()) .filter(index -> messages.get(index).contains(needle)) .boxed() // 把int转成Integer,方便收集到List .collect(Collectors.toList()); if (!allMatchIndices.isEmpty()) { System.out.println("所有匹配的索引:" + allMatchIndices); } else { System.out.println("没有找到包含'" + needle + "'的内层列表"); }
核心思路就是用IntStream直接操作外层列表的索引,这样就能把内层列表的存在性和它在外层的位置关联起来,而不是像原来的代码那样只遍历内层列表的元素。
内容的提问来源于stack exchange,提问作者Matt
相关产品推荐
相关产品推荐

