How does an Arraylist of Arraylist work? How to resort to an Arraylist of Arraylist?

Asked

Viewed 993 times

0

ArrayList<ArrayList<String>> ArrayList2;

How does an Arraylist work? How to resort to an Arraylist of Arraylist?

  • Could explain better what you want to do?

1 answer

2

The working doesn’t change. It’s 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 a for and the 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 );
            });
        }
    }
}

Demonstration: https://ideone.com/HSLcbp

  • Thank you for the reply.

  • @Adéritogt if solved, do not forget to mark as solved, this will help other people with the same doubt find the post more easily.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.