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;
}
You can put a
if (object != object2)
– Natan Fernandes
@And if you can have repeated elements in the list?
– hkotsubo
exactly, I’d like to do two
foreach
just to check if there are repeated items within aList<E>
– jotape
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"); }
– hkotsubo
And to know which ones repeat (not only if or not): https://stackoverflow.com/q/7414667
– hkotsubo
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.– jotape