1

I need to convert a CSVRecord to a List to get the position of an element.

So I used this :

List<CSVRecord> records = csvParser.getRecords();
int i = records.get(0).indexOf(element);

However, records.get(0) returns a List<CSVRecord> and not a List<String>...

Moreover I cannot use csvParser.getHeaderNames(); because after that I need to copy the file with the header.

T A
  • 1,677
  • 4
  • 21
  • 29
Royce
  • 1,557
  • 5
  • 19
  • 44

1 Answers1

2

Given the below function that I found on geeksforgeeks.com

public static <T> List<T> getListFromIterator(Iterator<T> iterator) { 
    Iterable<T> iterable = () -> iterator; 

    return StreamSupport 
              .stream(iterable.spliterator(), false) 
              .collect(Collectors.toList()); 
} 

and the fact that you can get an iterator from CVSRecords you can do

List<String> list = getListFromIterator(records.get(0).iterator());
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
  • This solutions seems to solve my problem. Thanks a lot. I have to check if this solution is not too much slow with a lot of data. – Royce Oct 30 '19 at 14:04