0

For a program I'm attempting to have a nested for loop repeat along the lines of this:

for(int i = 0;i < ArrayList.size();i++){
    for(int x = 0;x <ArrayList.get(i).length();x++){
        //stuff
    }
}

Essentially I want to repeat a for loop for every character in every index of an ArrayList but this solution doesn't seem to work. Any help appreciated!

Edit: the arraylist will only contain strings in my case

Sumtinlazy
  • 337
  • 5
  • 17

4 Answers4

3

Try using a For Each Loop such that:

int sumLength = 0;
ArrayList<String> r = new ArrayList<String>();
for(String s : r)
{
 sumLength += s.length();
}
return sumLength;

That will give you the sum of all the lengths in your ArrayList

JLiebman
  • 80
  • 7
1

Updated code:

You can use java8 streams to tackle this issue and not to mention is is null-safe. Here is an example.

import java.util.ArrayList;
import java.util.List;

public class NestedList {

    public static void main(String[] args) {

        List<String> list1 = new ArrayList<>();
        list1.add("JOHN");
        list1.add("JACK");
        list1.add("CYTHIA");
        list1.add("DANNY");

        list1.stream().forEach( str -> {
            char x;
            for (int i = 0; i < str.toCharArray().length; i++) {
                x = str.charAt(i);
                //do your struff
                System.out.println(x);
            }
        });

    }
}

The stream method by Java8 will handle the list where as you can use the toCharArray which will convert the string to arrays of character to handle each character.

Thina Garan
  • 106
  • 5
0

You can try this this way,

List<String> arrayList = new ArrayList();

arrayList.add("strings1");
arrayList.add("strings2");

for(int i = 0;i < arrayList.size();i++){
    for(int x = 0;x <arrayList.get(i).length();x++){
          //stuff
    }
}
Anuradha
  • 570
  • 6
  • 20
0

all your logic is correct but there is mistake with the syntax, you use Class name instead of object reference, ie, change ArrayList to the ArrayList reference variable in your code.

(ArrayList.size() to list.size())

change

for(int i = 0;i < ArrayList.size();i++){
    for(int x = 0;x <ArrayList.get(i).length();x++){
        //stuff
    }
}

to

ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add("mango");
list.add("orange");
for(int i = 0;i < list.size();i++){
        for(int x = 0;x <list.get(i).length();x++){
            //stuff
        }
}