【问题标题】:Iterating arraylist until find an specific character and stop the iteration [duplicate]迭代arraylist直到找到一个特定的字符并停止迭代[重复]
【发布时间】:2021-12-07 09:33:51
【问题描述】:

我正在尝试迭代一个数组列表,然后在它找到一个字符时让它停止,在这种情况下是一个逗号。这就是我所拥有的:

这是数组列表:

List<String> collection = Arrays.asList(new String[]{"I", "f", " ", "y", "o", "u", " ", "g", "e", "t", " ", "a", " ", "t", "e", "x", "t", " ", "m", "e", "s", "s", "a", "g", "e", " ", "f", "r", "o", "m", " ", "a", "n", " ", "e", "m", "a", "i", "l", " ", "a", "d", "d", "r", "e", "s", "s", " ", "o", "r", " ", "n", "u", "m", "b", "e", "r", " ", "y", "o", "u", " ", "d", "o", "n", "'", "t", " ", "r", "e", "c", "o", "g", "n", "i", "z", "e", ",", " ", "i", "t", "'", "s", " ", "p", "r", "o", "b", "a", "b", "l", "y", " ", "b", "e", "s", "t", " ", "t", "o", " ", "i", "g", "n", "o", "r", "e", " ", "i", "t"});

这是我在 main 上使用的方法:showUntil();

private static void showUntil() {

    for(String g : collection){
        if(g.equals(",")){
            System.out.println(g);
        }

    }
} 

我在这个练习中使用 java。

【问题讨论】:

标签: java arraylist collections iterator


【解决方案1】:

您可以使用indexOf 函数并迭代直到该索引。这是一种方法

List<String> collection = Arrays.asList(new String[]{"I", "f", " ", "y", "o", "u", " ", "g", "e", "t", " ", "a", " ", "t", "e", "x", "t", " ", "m", "e", "s", "s", "a", "g", "e", " ", "f", "r", "o", "m", " ", "a", "n", " ", "e", "m", "a", "i", "l", " ", "a", "d", "d", "r", "e", "s", "s", " ", "o", "r", " ", "n", "u", "m", "b", "e", "r", " ", "y", "o", "u", " ", "d", "o", "n", "'", "t", " ", "r", "e", "c", "o", "g", "n", "i", "z", "e", ",", " ", "i", "t", "'", "s", " ", "p", "r", "o", "b", "a", "b", "l", "y", " ", "b", "e", "s", "t", " ", "t", "o", " ", "i", "g", "n", "o", "r", "e", " ", "i", "t"});
         
for(String chr : collection.subList(0, collection.indexOf(","))) {
    System.out.println(chr);
}

如果你想更正你写的代码,你需要在找到下面这样的匹配时退出循环

for(String g : collection) {
    if(g.equals(",")) {
        System.out.println(g);
        break; //exit the loop if comma is found!
    }
}
        

【讨论】:

  • 第一个成功了,谢谢!
  • 性能方面,这是一个糟糕的选择。当一次遍历就足够时,它会遍历列表两次,并创建一个不必要的一次性对象。在调用它们之前,您需要了解每个库方法的作用。
猜你喜欢
  • 1970-01-01
  • 2023-03-29
  • 2021-11-29
  • 2011-09-11
  • 2018-01-09
  • 2015-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多