Verificar com Loop Manual
Na etapa anterior, usamos o método containsAll() conveniente para verificar um subconjunto. Embora containsAll() seja eficiente, é útil entender como você realizaria essa verificação manualmente usando um loop. Isso aprofundará sua compreensão de como os métodos de coleção podem funcionar internamente.
Vamos adicionar um novo método ao nosso arquivo SubsetCheck.java para realizar a verificação de subconjunto manualmente. Abra ~/project/SubsetCheck.java no editor WebIDE.
Adicione o seguinte método dentro da classe SubsetCheck, mas fora do 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 novo método isSubsetManual recebe duas listas como entrada. Em seguida, ele percorre cada element em subList. Dentro do loop, ele verifica se mainList contém o element atual usando o método contains(). Se encontrar até mesmo um elemento em subList que não está em mainList, ele sabe imediatamente que subList não é um subconjunto e retorna false. Se o loop terminar sem encontrar nenhum elemento em subList que esteja faltando em mainList, significa que todos os elementos estão presentes, e o método retorna true.
Agora, vamos chamar este novo método de nosso método main para comparar seu resultado com containsAll(). Modifique o método main em SubsetCheck.java para incluir chamadas para 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;
}
}
Salve o arquivo SubsetCheck.java modificado.
Agora, compile o código atualizado no Terminal:
javac SubsetCheck.java
E execute o programa novamente:
java SubsetCheck
Você deverá ver uma saída semelhante a esta, mostrando que tanto o método containsAll() quanto nosso método de loop manual produzem os mesmos 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
Esta etapa demonstra que você pode obter o mesmo resultado que containsAll() iterando pelo potencial subconjunto e verificando a presença de cada elemento na lista principal. Embora containsAll() seja geralmente preferido por sua concisão e possíveis otimizações de desempenho na biblioteca Java, a compreensão da abordagem manual é valiosa para o aprendizado.