如何遍历行的迭代器

问题描述

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

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 次? 谢谢

解决方法

我建议使用 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;
    
}