3.0 / 5
Hola buenas a todos, hoy les comparto un pequeño tutorial, extraÃdo del Blog de Spring.io, y que me pareció muy interesando para repasar un poco.
Recuerdo que ejercicios como este pedÃan en la universidad para los parciales, y las cosas se hacÃan de forma muy diferentes, usando muchas lineas de código.
Las colecciones de Java ofrecen una solución simple para quitar todos los elementos nulos en una lista.
Usando un While
@Test public void givenListContainsNulls_whenRemovingNullsWithPlainJava_thenCorrect() { List<Integer> list = Lists.newArrayList(null, 1, null); while (list.remove(null)); assertThat(list, hasSize(1)); }
Otra forma un poco mas sencillo de hacer seria de la siguiente forma:
@Test public void givenListContainsNulls_whenRemovingNullsWithPlainJavaAlternative_thenCorrect() { List<Integer> list = Lists.newArrayList(null, 1, null); list.removeAll(Collections.singleton(null)); assertThat(list, hasSize(1)); }
Como vemos, ambos métodos modifican directamente la lista, y no nos hizo falta usar otra lista para pasar los objetos no nulos.
Sacar nulos de una lista usando Google Guava.
Podemos eliminar objetos nulos de nuestra lista usando predicados: “Predicates”
@Test public void givenListContainsNulls_whenRemovingNullsWithGuavaV1_thenCorrect() { List<Integer> list = Lists.newArrayList(null, 1, null); Iterables.removeIf(list, Predicates.isNull()); assertThat(list, hasSize(1)); }
Si lo que queremos es no modificar la lista original, podemos usar algo como el siguiente código:
@Test public void givenListContainsNulls_whenRemovingNullsWithGuavaV2_thenCorrect() { List<Integer> list = Lists.newArrayList(null, 1, null, 2, 3); List<Integer> listWithoutNulls = Lists.newArrayList( Iterables.filter(list, Predicates.notNull())); assertThat(listWithoutNulls, hasSize(3)); }
Sacar nulos de una lista usando Apache Commons Collection
Apache Commons nos provee también de herramientas que nos pueden ser muy útiles, veamos un ejemplo simple de como sacar nulos de nuestra list:
@Test public void givenListContainsNulls_whenRemovingNullsWithCommonsCollections_thenCorrect() { List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null); CollectionUtils.filter(list, PredicateUtils.notNullPredicate()); assertThat(list, hasSize(3)); }
Sacar nulos de una lista usando Lambdas (Java 8)
Vamos a ver ahora como sacar nulos de nuestra list usando lambdas de java 8
@Test public void givenListContainsNulls_whenFilteringParallel_thenCorrect() { List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null); List<Integer> listWithoutNulls = list.parallelStream() .filter(Objects::nonNull) .collect(Collectors.toList()); } @Test public void givenListContainsNulls_whenFilteringSerial_thenCorrect() { List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null); List<Integer> listWithoutNulls = list.stream() .filter(Objects::nonNull) .collect(Collectors.toList()); } public void givenListContainsNulls_whenRemovingNullsWithRemoveIf_thenCorrect() { List<Integer> listWithoutNulls = Lists.newArrayList(null, 1, 2, null, 3, null); listWithoutNulls.removeIf(Objects::isNull); assertThat(listWithoutNulls, hasSize(3)); }
Como pueden ver, en los dos primeros métodos, usamos stream y filter para asar directamente la lista sin nulos a la nueva listWithoutNulls.
En el tercer método aplicamos “removeIf” a la misma lista y queda limpia de nulos. Una solución mas rápida, usando menos código.
Como podrán ver, tenemos muchas formas, para este caso, sacar objetos null de nuestro list. Podemos usar el que nos sea mas útil, eso queda en cada uno.
Espero les guste el articulo.
Origen: Removing all nulls from a List in Java | Baeldung