How does an ArrayList ArrayList work? How to use an ArrayList ArrayList?

0
ArrayList<ArrayList<String>> ArrayList2;

How does an ArrayList ArrayList work? How to use an ArrayList ArrayList?

    
asked by anonymous 10.05.2018 / 04:57

1 answer

2

Running does not change. It is just an object storing another object of the same type (roughly).

To go through the lists and sublists just use two (or one of each):

  • for
  • while
  • forEach
  • do..while
  • Iterator
  • Stream etc.

Below I used with for and forEach (lambda expression of Java 8).

import java.util.ArrayList;

class HelloWorld
{   
    public static void main(String[] args){

        /* Lista Final */
        ArrayList<ArrayList<String>> List = new ArrayList<ArrayList<String>>() {{

            /* Cria uma List de frutas */
            add( new ArrayList<String>() {{
                add("Abacaxi");
                add("Banana");
                add("Cajá");
                add("Caqui");
            }} );

            /* Cria uma List de armas */
            add( new ArrayList<String>() {{
                add("Parafal");
                add("M4");
                add("PT938");
                add("AR-15");
            }} );

            /* Cria uma List de bandas */
            add( new ArrayList<String>() {{
                add("Evanescence");
                add("Linkin Park");
                add("Epica");
                add("Xandria");
            }} );
        }};

        /* Percorre a primeira lista */
        for (int i = 0; i < List.size(); i++) {

            /**
             * Percorre as sublistas utilizando expressão Lambda (Java 8)
             * Caso não utilize Java 8, substitua por um 'for'
             */
            List.get(i).forEach( x -> {
                System.out.println( x );
            });
        }
    }
}

Demo: link

    
10.05.2018 / 06:40