Eliminar elementos de una Lista que satisfagan el predicado dado en Java

A continuación se muestran los métodos para eliminar de manera eficiente elementos de una lista que satisfacen una condición de predicado:
 

p  ==> Predicate, specifying the condition
l  ==> List, from which element to be removed

Usando iterador

El siguiente programa demuestra la eliminación de elementos nulos de la lista, utilizando el Predicado 
 

Java

// Java Program to remove nulls
// from a List using iterator and Predicate
import java.util.function.Predicate;
import java.util.*;
 
class GFG {
 
    // Generic function to remove Null Using Iterator
    public static <T> List<T>
    removeNullUsingIterator(List<T> l, Predicate<T> p)
    {
 
        // Create an iterator from the l
        Iterator<T> itr = l.iterator();
 
        // Find and remove all null
        while (itr.hasNext()) {
 
            // Fetching the next element
            T t = itr.next();
 
            // Checking for Predicate condition
            if (!p.test(t)) {
 
                // If the condition matches,
                // remove that element
                itr.remove();
            }
        }
 
        // Return the null
        return l;
    }
 
    public static void main(String[] args)
    {
 
        // Create the l with null values
        List<String> l = new ArrayList<>(
               Arrays.asList("Geeks",
                             null,
                             "forGeeks",
                             null,
                             "A computer portal"));
 
        // Print the list
        System.out.println("List with null values: " + l);
 
        // Creating a Predicate condition checking for null
        Predicate<String> isNull = item -> Objects.nonNull(item);
 
        // Removing nulls using iterator and Predicate
        l = removeNullUsingIterator(l, isNull);
 
        // Print the list
        System.out.println("List with null values removed: " + l);
    }
}
Producción

List with null values: [Geeks, null, forGeeks, null, A computer portal]
List with null values removed: [Geeks, forGeeks, A computer portal]

Complejidad del tiempo: O(N^2)

Complejidad del espacio: O(N)

Usando List.removeAll()

En este método, se utiliza una colección que contiene elementos que se eliminarán para eliminar esos elementos del l original. Requiere crear una colección con los elementos requeridos usando una condición Predicado. Después de hacer esto, se busca el l original para esta colección y se eliminan todas las instancias de la misma.
 

Java

// Java Program to remove 10
// from a List using List.removeAll() and Predicate
import java.util.function.Predicate;
import java.util.*;
 
class GFG {
 
    // Generic function to remove elements using Predicate
    public static <T> List<T>
    removeElements(List<T> l, Predicate<T> p)
    {
 
        // Create collection using Predicate
        Collection<T> collection = new ArrayList<>();
 
        for (T t : l) {
            if (p.test(t)) {
                collection.add(t);
            }
        }
 
        // Print the list
        System.out.println("Collection to be removed: " + collection);
 
        // Removing 10 using List.removeAll()
        // passing a collection
        l.removeAll(collection);
 
        // Return the list
        return l;
    }
 
    public static void main(String[] args)
    {
 
        // Create a list with null values
        List<String> l = new ArrayList<>(
            Arrays.asList("1", "10", "15", "10", "12", "5", "10", "20"));
 
        // Print the list
        System.out.println("Original List: " + l);
 
        // Creating a Predicate condition checking for 10
        Predicate<String> is10 = i -> (i == "10");
 
        // Removing using Predicate
        l = removeElements(l, is10);
 
        // Print the list
        System.out.println("Updated List: " + l);
    }
}
Producción

Original List: [1, 10, 15, 10, 12, 5, 10, 20]
Collection to be removed: [10, 10, 10]
Updated List: [1, 15, 12, 5, 20]

Uso de Lambdas (Java 8)

El método Stream.filter() se puede usar en Java 8 y devuelve un flujo que consta de los elementos 
que coinciden con la condición de predicado dada.
 

Java

// Java Program to remove nulls
// from a List using Java 8
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.*;
 
class GFG {
 
    // Generic function to remove elements using Predicate
    public static <T> List<T>
    removeElements(List<T> l, Predicate<T> p)
    {
 
        // Removing nulls using Java Stream
        // using Predicate condition in lambda expression
        l = l.stream()
                   .filter(p)
                   .collect(Collectors.toList());
 
        // Return the list
        return l;
    }
 
    public static void main(String[] args)
    {
 
        // Create a list with null values
        List<String> l = new ArrayList<>(
            Arrays.asList("Geeks",
                          null,
                          "forGeeks",
                          null,
                          "A computer portal"));
 
        // Print the list
        System.out.println("List with null values: " + l);
 
        // Creating a Predicate condition checking for null
        Predicate<String> isNull = i -> (i != null);
 
        // Removing using Predicate
        l = removeElements(l, isNull);
 
        // Print the list
        System.out.println("List with null values removed: " + l);
    }
}
Producción

List with null values: [Geeks, null, forGeeks, null, A computer portal]
List with null values removed: [Geeks, forGeeks, A computer portal]

Usando removeIf()

Como sugiere el nombre, es un método directo para eliminar todos los elementos que satisfacen el predicado dado.
 

Java

// Java Program to remove nulls
// from a List using Java 8
import java.util.function.Predicate;
import java.util.*;
 
class GFG {
 
    // Generic function to remove elements using Predicate
    public static <T> List<T>
    removeElements(List<T> l, Predicate<T> p)
    {
 
        // Removing nulls using Java Stream
        // using Predicate condition in removeIf()
        l.removeIf(x -> p.test(x));
 
        // Return the list
        return l;
    }
 
    public static void main(String[] args)
    {
 
        // Create a list with null values
        List<String> l = new ArrayList<>(
            Arrays.asList("Geeks",
                          null,
                          "forGeeks",
                          null,
                          "A computer portal"));
 
        // Print the list
        System.out.println("List with null values: " + l);
 
        // Creating a Predicate condition checking for null
        Predicate<String> isNull = i -> (i == null);
 
        // Removing using Predicate
        l = removeElements(l, isNull);
 
        // Print the list
        System.out.println("List with null values removed: " + l);
    }
}
Producción

List with null values: [Geeks, null, forGeeks, null, A computer portal]
List with null values removed: [Geeks, forGeeks, A computer portal]

Publicación traducida automáticamente

Artículo escrito por RishabhPrabhu y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *