Sets.difference() de Guava devuelve una vista no modificable de la diferencia de dos conjuntos.
Sintaxis:
public static <E> Sets.SetView<E> difference(Set<E> set1, Set<?> set2)
Valor devuelto: este método devuelve un conjunto que contiene todos los elementos contenidos en conjunto1 y no contenidos en conjunto2.
Nota: Set2 también puede contener elementos que no están presentes en set1, estos simplemente se ignoran. El orden de iteración del conjunto devuelto coincide con el del conjunto1.
Ejemplo 1:
// Java code to show implementation of // Guava's Sets.difference() method import com.google.common.collect.Sets; import java.util.Set; class GFG { // Driver's code public static void main(String[] args) { // Creating first set named set1 Set<Integer> set1 = Sets.newHashSet(1, 2, 3, 4, 5, 6); // Creating second set named set2 Set<Integer> set2 = Sets.newHashSet(1, 3, 5, 7); // Using Guava's Sets.difference() method Set<Integer> diff = Sets.difference(set1, set2); // Displaying the unmodifiable view of // the difference of two sets. System.out.println("Set 1: " + set1); System.out.println("Set 2: " + set2); System.out.println("Difference between " + "Set 1 and Set 2: " + diff); } }
Producción:
Set 1: [1, 2, 3, 4, 5, 6] Set 2: [1, 3, 5, 7] Difference between Set 1 and Set 2: [2, 4, 6]
Ejemplo 2:
// Java code to show implementation of // Guava's Sets.difference() method import com.google.common.collect.Sets; import java.util.Set; class GFG { // Driver's code public static void main(String[] args) { // Creating first set named set1 Set<String> set1 = Sets .newHashSet("H", "E", "L", "L", "O", "G"); // Creating second set named set2 Set<String> set2 = Sets .newHashSet("L", "I", "K", "E", "G"); // Using Guava's Sets.difference() method Set<String> diff = Sets.difference(set1, set2); // Displaying the unmodifiable view of // the difference of two sets. System.out.println("Set 1: " + set1); System.out.println("Set 2: " + set2); System.out.println("Difference between " + "Set 1 and Set 2: " + diff); } }
Producción:
Set 1: [E, G, H, L, O] Set 2: [I, K, L, E, G] Difference between Set 1 and Set 2: [H, O]
Publicación traducida automáticamente
Artículo escrito por Sahil_Bansall y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA