I have an ArrayList full with String arrays that I can't figure out how to loop through. Iterators are new to me and even though I have used them in the past, I'm not sure what to do here.
Iterator<String[]> iterator = list.iterator();
while (iterator.hasNext()) {
String trip = "Till: " + iterator.next(0) + " | Från: " + list.get(4) + " | Kostar: " + list.get(1) +"kr | Avgår: " + list.get(2) + " | Ankomst Tid: " + list.get(3) + " | Antal bokningar: " + list.get(4);
This is some experimenting I am doing. I though that iterator.next() would return the StringArray on the current row so I have tried for example iterator.next(0). As I understand list.get(x) only gives me the row.
In the code above, I want every rows String Array at a certain index. Something like this:
for each row
system.out.println(String[2] +String[5]);
That is because you have a list of arrays, not a list of Strings.
List<String[]> list = //some data
for (String[] array : list){
System.out.println(array[3] + ":" + array[5]);
}
If you want to iterate over each string you will have to iterate twice.
List<String[]> list = //some data
for (String[] array : list){
for (String s : array){
System.out.println(s);
}
}
EDIT
The above is shorthand for using an iterator.
List<String[]> list = //some data
Iterator<String[]> itr = list.iterator();
while (itr.hasNext()){
String[] array = itr.next(); // You were just missing saving the value for reuse
System.out.println(array[3] + ":" + array[5]);
}
You can do this without having to worry about iterators in your code:
List<String[]> test = new ArrayList<>();
for(String[] array : test) {
//Iterate over inner array:
for(String s : array) {
System.out.println(s);
}
//or access directly
System.out.println(array[0]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With