views:

85

answers:

5

I am using OpenCSV to read data from a CSV file and am using some of the sample code from the homepage:

CSVReader reader = new CSVReader(new FileReader("stockInfo.csv"));
List myEntries = reader.readAll();

And i am now trying to loop through this list and print out each entry. But i cannot seem to figure out the code to perform this.

Could anyone explain to me how i am supposed to do this becuase i just cant seem to work it out.

A: 

Can't you do: 1)

for(int i = 0; i < myEntries.size(); i++){
  myEntries.get(i); // do something else here
}

or

2)

for(String s: myEntries)
   // Do work on s here
skaz
Read the doc (http://opencsv.sourceforge.net/api/au/com/bytecode/opencsv/CSVReader.html), yo. It's a list of arrays of Strings.
Christian Mann
ok, then String[]. Same point, yo.
skaz
A: 

Have you tried using an Iterator? It should be something like this:

Iterator it = myEntries.iterator();
while(it.hasNext()){
  System.out.println(it.next());
}
HED
Just use a for loop, it's less code.
Steve Kuo
+1  A: 

You should be using generics with CSVReader if possible. readAll() actually returns a List<String[]> and not a List<String>. Then, you just need to:

for (String[] row : myEntries) {
  System.out.println(Arrays.toString(row));
}
ColinD
+2  A: 

Assuming you want to output each entry of each line to it's own line:

    List<String[]> myEntries = reader.readAll();
    for (String[] lineTokens : myEntries) {
        for (String token : lineTokens) {
            System.out.println(token);
        }
    }
kaliatech
A: 

You can do something of this effect. I've added synchronization on iterator.

List<String[]> myEntries = reader.readAll();
Iterator<String[]> iter = myEntries.iterator();
synchronized (iter) {
    while (iter.hasNext()) {
        String[] items = iter.next();

        for (String item: items) { //foreach loop
            //Work with `item`
        }
    }
}
The Elite Gentleman
Your `synchronized` is useless because `iterator()` will return a new `Iterator` instance. So you're synchronizing on local variable that's not shared with any other thread.
Steve Kuo
@steve Kuo, it's an old habit...
The Elite Gentleman