Select from an array inside another array

Asked

Viewed 206 times

0

I own a ArrayList which has other ArrayList within it, I got through the following scrip on Groovy:

def i0 = listaTransportadoras.get([0]);
def i1 = listaTransportadoras.get(1);

logger.info(i0.toString());
logger.info(i1.toString());

Select the 1st and 2nd array that are inside this main array, but I need to get the indices that are inside each of these "subarrays", if you have an idea thank you.

2 answers

0

I didn’t quite understand the question, but you can easily access the elements of Arraylist like this:

def lista = [['a', 'b'], ['d', 'e'], ['c']]

lista[0] // Primeiro elemento da lista: primeira ArrayList => [a, b]
lista[0][0] // Primeiro elemento da primeira ArrayList => a
lista[0][1] // Segundo elemento da primeira ArrayList => b

lista[0].size // Número de elementos na primeira ArrayList => 2
lista[2].size // Número de elementos na terceira (e última) ArrayList => 1
  • I posted an answer to show how I solved my problem, but thanks for the feedback

0


I was able to access the data from the subArrays as follows:

List item = new ArrayList(); // Array que irá receber os registros de cada subArray

def x = 0;
def i = listaTransportadoras.size(); //Quantidade de colunas nos subArrays
logger.info("Quantidade: "+i.toString());

while (x <= (i - 1)){
    item = listaTransportadoras.get(x); 
    transportadoras.codigo.add(item.get(0));
    transportadoras.nome.add(item.get(1));
    logger.info("Codigo Registro: "+item.get(0).toString());
    logger.info("Nome Registro: "+item.get(1).toString());
    x++;
    item.clear();
}
  • It seems like a lot of code just to loop. I also noticed that you use Java native elements more than the Groovy way. Looping with Groovy is very easy. Using while and others is less desirable than using iterators like each: lista.each { println it }, where list is defined as lista = [['a', 'b'], ['c', 'd', 'e'], ['f']] and the result would be each internal list on its own line: [a, b]&#xA;[c, d, e]&#xA;[f]

Browser other questions tagged

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