java foreach saltar primera iteración


¿Hay una forma elegante de omitir la primera iteración en un bucle foreach Java5 ?

Ejemplo de pseudo-código:

for ( Car car : cars ) {     
   //skip if first, do work for rest
   .
   .
}
Author: Alex, 2011-04-19

10 answers

No lo llamaría elegante, pero quizás mejor que usar un" primer " booleano:

for ( Car car : cars.subList( 1, cars.size() ) )
{
   .
   .
}

Aparte de eso, probablemente ningún método elegante.  

 53
Author: Sean Adkinson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-26 09:30:09

Con la nueva Java 8 Stream API en realidad se vuelve muy elegante. Simplemente use el método skip():

cars.stream().skip(1) // and then operations on remaining cars
 37
Author: Kao,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-02 11:06:46

Use Guayaba Iterables.skip().

Algo como:

for ( Car car : Iterables.skip(cars, 1) ) {     
    // 1st element will be skipped
}

(Obtuve esto del final de la respuesta de msandiford y quería que fuera una respuesta independiente)

 27
Author: yop83,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:25
for (Car car : cars)
{
   if (car == cars[0]) continue;
   ...
}

Lo suficientemente elegante para mí.

 24
Author: elekwent,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-04-19 00:14:17

El código de SeanA tiene un pequeño error: el segundo argumento para sublist se trata como un índice exclusivo, por lo que solo podemos escribir

for (Car car : cars.subList(1, cars.size()) {
   ...
}

(Parece que no puedo comentar las respuestas, de ahí la nueva respuesta. ¿Necesito cierta reputación para hacer eso?)  

 17
Author: Daniel Lubarov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-26 09:29:45

Llegué un poco tarde a esto, pero podrías usar un método de ayuda, algo como:

public static <T> Iterable<T> skipFirst(final Iterable<T> c) {
    return new Iterable<T>() {
        @Override public Iterator<T> iterator() {
            Iterator<T> i = c.iterator();
            i.next();
            return i;
        }
    };
}

Y úsalo algo como esto:

public static void main(String[] args) {
    Collection<Integer> c = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
    for (Integer n : skipFirst(c)) {
        System.out.println(n);
    }
}

Generalizar para omitir " n " se deja como un ejercicio para el lector:)


EDIT : En una inspección más cercana, veo que la guayaba tiene un Iterables.skip(...) aquí .

 6
Author: msandiford,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-21 22:44:24

No soy una persona java, pero se puede utilizar:

for ( Car car : cars.tail() ) de Java.util via Groovy JDK

 3
Author: Preet Sangha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-04-18 23:52:07

Elegante? En realidad no. Usted tendría que comprobar / establecer un booleano.

El bucle for-each es para todos los propósitos prácticos una sintaxis elegante para usar un iterador. Es mejor usar un iterador y avanzar antes de comenzar el bucle.

 1
Author: Brian Roach,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-04-18 23:47:39

No tan elegante pero trabajar con iteradores

Iterator<XXXXX> rows = array.iterator();
if (rows.hasNext()){
    rows.next();
}
for (; rows.hasNext();) {
    XXXXX row = (XXXXX) rows.next();
}
 1
Author: Angel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-03 18:27:14

Esto podría no ser elegante, pero uno podría inicializar una variable entera fuera del bucle for e incrementarla con cada iteración dentro del bucle. Su programa solo se ejecutará si el contador es mayor que 0.

int counter = 0;
for ( Car car : cars ) {
    //skip if first, do work for rest
    if(counter>0){
        //do something
    }
    counter++;
}
 1
Author: Benjamin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-17 09:34:57