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 cann开发者_运维技巧ot 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.
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);
}
}
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
Have you tried using an Iterator? It should be something like this:
Iterator it = myEntries.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
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));
}
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`
}
}
}
In Java 8 and above you can also do
List<String> s = new LinkedList<>();
s.stream().forEach(System.out::print);
or
List<String> s = new LinkedList<>();
s.stream().forEach(s ->
System.out.print(s)
);
It is possible to use paralleStream() instead or stream() to make parallel execution. There are a lot of articles on the internet about which will execute quicker and the answer is : "it depends" (mostly on the number of items in the list)
精彩评论