How to browse lists?

Asked

Viewed 8,611 times

2

I wanted a solution to go through a practical list.

You don’t need to show any results as I will need to scroll through a list of people (objects) and generate accounts receivable from each one, but first I need to know how to scroll through this list.

  • 1

    Why limit yourself to ArrayList ? The answer will be valid for any List.

3 answers

3


Supposing listaPessoas is a list of the object Pessoa.

Thus:

for(Pessoa pessoa : listaPessoas)
{
     pessoa.fazerAlgumaCoisa();
}

Or else

for(int i = 0; i < listaPessoas.size(); i++)
{
    listaPessoas.get(i).fazerAlgumaCoisa();
}
  • 2

    A carelessness: listaPessoas[i] is for arrays. It would be listaPessoas.get(i).fazerAlgumaCoisa();

  • Thanks @Piovezan. My fault, it’s the custom with C#.

1

Only by complementing the Renan response, it is not necessary to use the.stream() list to use the foreach method, if the list you want to iterate implement the Collection interface you can use the direct foreach, example:

lista.forEach(elemento -> /* faz algo */);
  • Well remembered, +1.

0

In addition to the jbueno answers, you can also use a iterator to traverse an Arraylist.

It should be noted that the foreach is a syntactic sugar form of the iterator. Therefore, both have the same result. Just out of curiosity.

Browser other questions tagged

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