Tengo dos arrayLists por ahora, y quiero hacer iteraciones cruzadas de ellos (básicamente, primero iterar el primer elemento en el primer arrayList y luego iterar el primer elemento en el segundo arrayList , luego iterar el segundo elemento en el primer arrayList etc.). Me pregunto cómo debo lograr esta funcionalidad.
Aquí hay un código de prueba simple:
public static void main(String[] args) { ArrayList first = new ArrayList(); first.add("a"); first.add("c"); first.add("e"); ArrayList second = new ArrayList(); second.add("b"); second.add("d"); System.out.println(first); System.out.println(second); } Básicamente, me gustaría extraer primero el String a y hacer un poco de codificación, luego String b , luego String c , luego d y e (tenga en cuenta que la cantidad de elementos en el segundo arrayList es siempre uno más pequeño que el primero).
Cualquier pista será muy apreciada :)
Puede iterar ambas listas desde 0 hasta second.size() , como dijo que el segundo siempre es más pequeño.
Y con un segundo for-loop iterar los elementos restantes desde second.size() hasta first.size()
ArrayList<String> first = new ArrayList<>(); first.add("a"); first.add("c"); first.add("e"); first.add("f"); first.add("g"); ArrayList<String> second = new ArrayList<>(); second.add("b");second.add("d"); for(int i = 0; i < second.size(); i++){ System.out.println(first.get(i).toUpperCase()); System.out.println(second.get(i).toLowerCase()); } //iterate the rest elements remained in first for(int i = second.size(); i < first.size(); i++){ System.out.println(first.get(i).toUpperCase()); }Según la explicación dada en uno de los comentarios, la Lista first debe cambiarse de nombre a actions y la Lista en second debe ser moves . Además, siempre hay una action final después del último move , y el procesamiento siempre comienza con una acción.
Pruebe esto (pero reemplace el '?' por algo útil primero):
public final void process( final List<?> a, final List<?> m ) { if( a.size() != m.size() + 1 ) throw IllegalArgumentException( … ); final Queue<?> actions = new LinkedList<>( a ); final Queue<?> moves = new LinkedList<>( m ); while( !moves.isEmpty() ) { final var action = actions.remove(); final var move = moves.remove(); doAction( action ); doMove( move ); } final var action = actions.remove(); doAction( action ); assert actions.isEmpty(); assert moves.isEmpty(); }Llama a esto como
process( first, second ); Por supuesto, puede evitar las variables locales utilizando el valor de retorno de Queue.remove() como argumento para los métodos do…() .
Podría usar un bucle for con dos contadores e iterar desde 0 hasta first.length
counterForFirst (i en el bucle foor) = 0; contador por segundo = 0;
dentro del ciclo, también incrementaría counterForSecond.
Para evitar ArrayIndexOutOfBoundsException, puede verificar if(counterForSecond < second.length ) en cada itiración.
for (int counterForFirst = 0; counterForFirst < first.size(); counterForFirst++) { // action on first[counterForFirst] if(counterForFirst < seconds.length) { // action on seconds counterForSecond ++ ; } }