Verificar con un bucle manual
En el paso anterior, utilizamos el conveniente método containsAll()
para comprobar si una lista es un subconjunto de otra. Si bien containsAll()
es eficiente, es útil entender cómo se realizaría esta comprobación manualmente utilizando un bucle. Esto profundizará tu comprensión de cómo funcionan internamente los métodos de las colecciones.
Vamos a agregar un nuevo método a nuestro archivo SubsetCheck.java
para realizar la comprobación de subconjunto manualmente. Abre ~/project/SubsetCheck.java
en el editor del WebIDE.
Agrega el siguiente método dentro de la clase SubsetCheck
, pero fuera del método main
:
// Method to manually check if subList is a subset of mainList
public static boolean isSubsetManual(List<String> mainList, List<String> subList) {
// Iterate through each element in the subList
for (String element : subList) {
// If the mainList does NOT contain the current element from subList,
// then subList is not a subset, and we can return false immediately.
if (!mainList.contains(element)) {
return false;
}
}
// If we have checked all elements in subList and found them all in mainList,
// then subList is a subset.
return true;
}
Este nuevo método isSubsetManual
toma dos listas como entrada. Luego recorre cada element
en la subList
. Dentro del bucle, verifica si la mainList
contiene el element
actual utilizando el método contains()
. Si encuentra incluso un elemento en subList
que no está en mainList
, inmediatamente sabe que subList
no es un subconjunto y devuelve false
. Si el bucle finaliza sin encontrar ningún elemento en subList
que falte en mainList
, significa que todos los elementos están presentes y el método devuelve true
.
Ahora, llamemos a este nuevo método desde nuestro método main
para comparar su resultado con containsAll()
. Modifica el método main
en SubsetCheck.java
para incluir llamadas a isSubsetManual
:
import java.util.ArrayList;
import java.util.List;
public class SubsetCheck {
public static void main(String[] args) {
// Create the main list
List<String> mainList = new ArrayList<>();
mainList.add("Apple");
mainList.add("Banana");
mainList.add("Cherry");
mainList.add("Date");
// Create a potential subset list
List<String> subList = new ArrayList<>();
subList.add("Banana");
subList.add("Cherry");
// Check if subList is a subset of mainList using containsAll()
boolean isSubsetContainsAll = mainList.containsAll(subList);
// Check if subList is a subset of mainList using manual loop
boolean isSubsetManualCheck = isSubsetManual(mainList, subList);
// Print the result
System.out.println("Main List: " + mainList);
System.out.println("Sub List: " + subList);
System.out.println("Is subList a subset of mainList (containsAll)? " + isSubsetContainsAll);
System.out.println("Is subList a subset of mainList (manual check)? " + isSubsetManualCheck);
// Create another list that is not a subset
List<String> anotherList = new ArrayList<>();
anotherList.add("Banana");
anotherList.add("Grape"); // Grape is not in mainList
// Check if anotherList is a subset of mainList using containsAll()
boolean isAnotherSubsetContainsAll = mainList.containsAll(anotherList);
// Check if anotherList is a subset of mainList using manual loop
boolean isAnotherSubsetManualCheck = isSubsetManual(mainList, anotherList);
// Print the result for the second check
System.out.println("\nAnother List: " + anotherList);
System.out.println("Is anotherList a subset of mainList (containsAll)? " + isAnotherSubsetContainsAll);
System.out.println("Is anotherList a subset of mainList (manual check)? " + isAnotherSubsetManualCheck);
}
// Method to manually check if subList is a subset of mainList
public static boolean isSubsetManual(List<String> mainList, List<String> subList) {
// Iterate through each element in the subList
for (String element : subList) {
// If the mainList does NOT contain the current element from subList,
// then subList is not a subset, and we can return false immediately.
if (!mainList.contains(element)) {
return false;
}
}
// If we have checked all elements in subList and found them all in mainList,
// then subList is a subset.
return true;
}
}
Guarda el archivo SubsetCheck.java
modificado.
Ahora, compila el código actualizado en la Terminal:
javac SubsetCheck.java
Y ejecuta el programa nuevamente:
java SubsetCheck
Deberías ver una salida similar a esta, que muestra que tanto el método containsAll()
como nuestro método de bucle manual producen los mismos resultados:
Main List: [Apple, Banana, Cherry, Date]
Sub List: [Banana, Cherry]
Is subList a subset of mainList (containsAll)? true
Is subList a subset of mainList (manual check)? true
Another List: [Banana, Grape]
Is anotherList a subset of mainList (containsAll)? false
Is anotherList a subset of mainList (manual check)? false
Este paso demuestra que se puede lograr el mismo resultado que con containsAll()
recorriendo el posible subconjunto y comprobando la presencia de cada elemento en la lista principal. Si bien containsAll()
es generalmente preferido por su concisión y posibles optimizaciones de rendimiento en la biblioteca de Java, entender el enfoque manual es valioso para el aprendizaje.