0

Im trying to add string values inside a 2D list. Was able to add the 1st layer using this:

List<List<String>> twodaray = new ArrayList<List<String>>();
    List<String> x = new ArrayList<String>();


   for ( int i = 0, m = 1; i < attribteList.size(); i = i+2, m = m+2) {
       String attributeName = attribteList.get(i);
       x.add(attributeName);
   }
   twodaray.add(x);

   for(List<String> ls : twodaray) {
       System.out.println(Arrays.deepToString(ls.toArray()));
   }

Was wondering how can I access the inner layer of the ArrayList like print it out (sysout) or even adding values to it? Something like this.

    for(List<String> ls : twodaray) {
        System.out.println(Arrays.deepToString(ls.toArray()));
        for(List<List<String>> ls2d : ls) {
           if (ls = something) {
               ls2d.add(something);
           }
        }
    }

Kinda new to using this 2 dimensional list and any help is greatly appreciated. ty...

user3736748
  • 185
  • 2
  • 3
  • 15

2 Answers2

0

It's not apparent what exactly you're trying to do, but, this code is close other than a couple of mistakes (= should be .equals(), and the inner and outer foreach loops were somewhat mixed up ):

List<String> a = new List<String>();
a.add("Hello");

List<String> b = new List<String>();
b.add("World");

List<List<String>> ls = new List<List<String>>();
ls.add(a);
ls.add(b);

//The outer part (ie. one List of a List of strings
for(List<String> ls : twodaray) {

    //The inner part (ie. one string for each list of strings)
    for(String str : ls) {

       //Check two things for equality (.equals() for strings)
       if (str.equals("Hello")) {
           //Adding "something" to the list (that str is in);
           ls.add("something");
       }
    }
}

This question is pretty similar to this.

Community
  • 1
  • 1
Ricky Mutschlechner
  • 4,291
  • 2
  • 31
  • 36
0

I think it should be like this.

for(List<String> ls : twodray) { // twodaray is a List<List<String>>
        System.out.println(ls); // Yes you can simple sysout
        for(String str : ls) { // ls is a List<String>
           if (str.equals("something")) {
               // do something.
           }
        }
    }

I think its better to understand the structure of this 2D ArrayList. The 2D ArrayList's elements are 1D ArrayLists. 1D ArrayList's elements are the Strings.

enter image description here

If you are modifying the same arrayList (specially removes values) while reading it better to use CopyOnWriteArrayList.

ironwood
  • 8,936
  • 15
  • 65
  • 114