如何遍历行的迭代器

时间:2021-04-05 23:53:09

标签: java

我想迭代我的迭代器的前几行,我正在尝试像下面这样迭代所有文件:

Dataset<Row> DF = spark.read().format("csv").load("longfile.csv");
Iterator<Row> iter = DF.toLocalIterator();


while (iter.hasNext()) { // i want a condition here to iterate only over the 20 first lines of my CSV
    Row item = iter.next();
    System.out.println(item);
}


    

我的问题是如何将迭代限制为仅 20 次? 谢谢

1 个答案:

答案 0 :(得分:1)

我建议使用 int 计数并在计数完成时中断:

Dataset<Row> DF = spark.read().format("csv").load("longfile.csv");
Iterator<Row> iter = DF.toLocalIterator();

int count = 0;

while (iter.hasNext()) { // i want a condition here to iterate only over the 20 first lines of my CSV
    count++;
    Row item = iter.next();
    System.out.println(item);
    if(count > 20) break;
    
}
相关问题