Compare equal values in two ArrayList java

1

If I have two ArrayList different in my code as I can do to see what values are equal for example:

ArrayList a=new ArrayList();
a.add("Juan");
a.add("Pedro");
a.add("Luis");
ArrayList b=new ArrayList();
b.add("Carlos");
b.add("Luis");
b.add("Juan");

I want to know which names are repeated and in what position they are.

    
asked by Ángel Hernández 08.06.2018 в 19:14
source

1 answer

-1

You must iterate the elements of an ArrayList and compare the content with the elements of the second ArrayList, if you determine that they are the same, you can print their position.

for(int i = 0; i< a.size(); i++){ //Itera elementos del primer ArrayList
    for(int j = 0; j< b.size(); j++){//Itera elementos del segundo ArrayList
           if(a.get(i).equals(b.get(j))){ //Compara si los valores son iguales.
               System.out.println("Elemento del array a \"" + a.get(i) + "\", posición: " + i + "  es igual a el elemento del array b  en la posición: " + j);
           }
    }
}

Based on the above and the values defined in your question you would have as output:

  

Element of the array to "John", position: 0 is equal to the element of the   array b in the position: 2 Element of the array "Luis", position: 2   is equal to the element of array b in the position: 1

    
answered by 08.06.2018 в 19:18