Scroll through a list to get the current element and the next

Asked

Viewed 33 times

1

How can I implement two for(Teste teste : lista) {} to go through the same list? And the second foreach would always have to look at the next item on this list?

I tried that way but he always compares the same object.

for (Object object : listaLinhas) {
    for (Object object2 : listaLinhas) {
        
    }
}
  • You can put a if (object != object2)

  • 1

    @And if you can have repeated elements in the list?

  • exactly, I’d like to do two foreach just to check if there are repeated items within a List<E>

  • 1

    John, to check for repeated items, a better way is to create a Set (that does not allow repeated elements) and see if the size is equal to the list: Set<Object> set = new HashSet<>(lista); if (set.size() == lista.size()) { System.out.println("Não há elementos repetidos"); } else { System.out.println("Há elementos repetidos"); }

  • 1

    And to know which ones repeat (not only if or not): https://stackoverflow.com/q/7414667

  • Yes, I tried to do this to check if an Id attribute was repeated in an object list. I used !set.add(obj.getId()) to check if this item is already in this hashset. However, it repeats itself in a non-linear way, at random moments in the list.

Show 1 more comment

1 answer

1


You don’t have to make a for inside each other. Just make a single loop, only using the indexes. Then you go from the first to the penultimate, and to get the next one, just pick up the following index:

for (int i = 0; i < lista.size() - 1; i++) {
    Object atual = lista.get(i);
    Object proximo = lista.get(i + 1);
    // usa o atual e proximo
    // ...
}

Another option is to get the Iterator from the list and pick up his elements, one by one:

Iterator<Object> it = lista.iterator();
Object atual = it.next(); // pega o primeiro
while (it.hasNext()) {
    Object proximo = it.next(); // pega o próximo

    // usa o atual e proximo
    // ...

    // atualiza o atual
    atual = proximo;
}

Or even, the same algorithm, but using the indexes:

Object atual = lista.get(0); // pega o primeiro
for (int i = 1; i < lista.size(); i++) { // for começa do segundo elemento
    Object proximo = lista.get(i); // pega o próximo

    // usa o atual e proximo
    // ...

    // atualiza o atual
    atual = proximo;
}
  • 1

    Thank you very much, I figured two foreach would not be necessary

Browser other questions tagged

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