7

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]);
Essej
  • 892
  • 6
  • 18
  • 33
  • 1
    There is a subtle difference in that the author is trying to determine how to use the Array value inside the loop. – cyroxis May 11 '16 at 15:50

4 Answers4

8

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]);
}
cyroxis
  • 3,661
  • 22
  • 37
1

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]);
}
StuPointerException
  • 7,117
  • 5
  • 29
  • 54
0
Iterator<String[]> iterator = list.iterator();
while (iterator.hasNext()) {
    String[] row = iterator.next();
    //Do stuff with row
}

If you're using a list, you can also use a for loop:

for(String[] row : list) {
    //Do stuff with row
}
Zircon
  • 4,677
  • 15
  • 32
-1

Each item in the ArrayList is a String[], so iterator.next() returns a String[]. Once you have that String array, you can access it like any other array with array index notation. item[0] is the first item in the array, item.length tells you how many items are in the array.

Where you're calling list.get(4) will also return an array of strings, which almost certainly isn't what you want in the output.

David
  • 2,602
  • 1
  • 18
  • 32