Java如何遍历ArrayList直到找到指定逗号字符后停止迭代
解决方案
方式1:修改原有增强for循环
你当前的代码缺失终止循环的逻辑,只需要在匹配到逗号的判断分支中添加break关键字即可终止遍历,根据你是否需要打印逗号前的元素,可选择对应写法:
- 需求为「打印所有元素直到遇到逗号为止(包含逗号)」,修改后代码如下:
private static void showUntil() { for(String g : collection){ System.out.println(g); if(g.equals(",")){ break; // 匹配到逗号后直接跳出循环,终止遍历 } } }
- 需求为「仅在遇到逗号时打印逗号,随后终止遍历」,修改后代码如下:
private static void showUntil() { for(String g : collection){ if(g.equals(",")){ System.out.println(g); break; } } }
方式2:Java 8+ Stream 简洁实现
利用Stream的短路操作特性,也可以更简洁的实现需求:
private static void showUntil() { // 遍历打印元素,匹配到逗号后自动终止处理 collection.stream() .peek(System.out::println) .anyMatch(item -> item.equals(",")); }
内容的提问来源于stack exchange,提问作者Andres Carroz
相关产品推荐
相关产品推荐

