Reputation: 1724
As I run this code, the iterator iter
is empty the second time I use it. I am instantiating iter
each time in the outer loop, but it does not help! That is, after the first iteration, the length of the iterable is zero!
Why is that so? And what is the general practice for this scenario that I am missing?
String path = "somefile.csv";
try {
Reader in = new FileReader(path);
Iterable<CSVRecord> records = CSVFormat.RFC4180.withHeader(MetadataExtractorForTables.HeaderType.class)
.withDelimiter('\t').parse(in);
// A stupid loop
for(int i = 0; i < 3; i++) {
Iterator<CSVRecord> iter = records.iterator();
System.out.println("---> " + Iterators.size(iter));
System.out.println("--> " + StreamSupport.stream(records.spliterator(), false).count());
/* ----------------------------------------
* here I would like to use the iterator
* in a (nested) loop
* ---------------------------------------- */
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The output looks like this:
---> 191
--> 0
---> 0
--> 0
---> 0
--> 0
Upvotes: 0
Views: 124
Reputation: 198321
Because it's an evil, contract-breaking Iterable.
From the docs:
It is not possible to go back, once a record has been parsed from the input stream.
You'll have to explicitly copy it into a List or the like.
Upvotes: 2