• SetUtils de colecciones de Apache Commons
• OrderedMap de colecciones de Apache Commons
• BidiMap de las colecciones de Apache Commons
• Una guía para las colecciones de Apache Commons CollectionUtils (artículo actual) • Apache Commons Collection MapUtils
• Guía de Apache Commons CircularFifoQueue
1. Información general
En pocas palabras, Apache CollectionUtils proporciona métodos de utilidad para operaciones comunes que cubren una amplia gama de casos de uso y ayuda a evitar escribir código repetitivo. La biblioteca apunta a versiones más antiguas de JVM porque actualmente, la API Stream de Java 8 proporciona una funcionalidad similar .
2. Dependencias de Maven
Necesitamos agregar la siguiente dependencia para comenzar con CollectionUtils:
org.apache.commons commons-collections4 4.1
La última versión de la biblioteca se puede encontrar aquí.
3. Configuración
Agregar vamos a clientes y Dirección clases:
public class Customer { private Integer id; private String name; private Address address; // standard getters and setters } public class Address { private String locality; private String city; // standard getters and setters }
También tendremos a mano las siguientes instancias de lista y cliente listas para probar nuestra implementación:
Customer customer1 = new Customer(1, "Daniel", "locality1", "city1"); Customer customer2 = new Customer(2, "Fredrik", "locality2", "city2"); Customer customer3 = new Customer(3, "Kyle", "locality3", "city3"); Customer customer4 = new Customer(4, "Bob", "locality4", "city4"); Customer customer5 = new Customer(5, "Cat", "locality5", "city5"); Customer customer6 = new Customer(6, "John", "locality6", "city6"); List list1 = Arrays.asList(customer1, customer2, customer3); List list2 = Arrays.asList(customer4, customer5, customer6); List list3 = Arrays.asList(customer1, customer2); List linkedList1 = new LinkedList(list1);
4. CollectionUtils
Repasemos algunos de los métodos más utilizados en la clase CollectionUtils de Apache Commons .
4.1. Agregar solo elementos no nulos
Podemos usar el método addIgnoreNull de CollectionUtils para agregar solo elementos no nulos a una colección proporcionada.
El primer argumento de este método es la colección a la que queremos agregar el elemento y el segundo argumento es el elemento que queremos agregar:
@Test public void givenList_whenAddIgnoreNull_thenNoNullAdded() { CollectionUtils.addIgnoreNull(list1, null); assertFalse(list1.contains(null)); }
Observe que el nulo no se agregó a la lista.
4.2. Clasificación de listas
Podemos utilizar intercalación método para cotejar dos listas ya clasificadas. Este método toma ambas listas, que queremos fusionar, como argumentos y devuelve una única lista ordenada:
@Test public void givenTwoSortedLists_whenCollated_thenSorted() { List sortedList = CollectionUtils.collate(list1, list2); assertEquals(6, sortedList.size()); assertTrue(sortedList.get(0).getName().equals("Bob")); assertTrue(sortedList.get(2).getName().equals("Daniel")); }
4.3. Transformando objetos
Podemos usar el método transform para transformar objetos de clase A en diferentes objetos de clase B. Este método toma una lista de objetos de clase A y un transformador como argumentos.
El resultado de esta operación es una lista de objetos de clase B:
@Test public void givenListOfCustomers_whenTransformed_thenListOfAddress() { Collection addressCol = CollectionUtils.collect(list1, new Transformer() { public Address transform(Customer customer) { return customer.getAddress(); } }); List addressList = new ArrayList(addressCol); assertTrue(addressList.size() == 3); assertTrue(addressList.get(0).getLocality().equals("locality1")); }
4.4. Filtrar objetos
Usando el filtro podemos eliminar los objetos que no satisfacen una condición determinada de una lista . El método toma la lista como primer argumento y un predicado como segundo argumento.
El método filterInverse hace lo contrario. Elimina objetos de la lista cuando el predicado devuelve verdadero.
Tanto filter como filterInverse devuelven verdadero si la lista de entrada fue modificada, es decir, si al menos un objeto fue filtrado fuera de la lista:
@Test public void givenCustomerList_WhenFiltered_thenCorrectSize() { boolean isModified = CollectionUtils.filter(linkedList1, new Predicate() { public boolean evaluate(Customer customer) { return Arrays.asList("Daniel","Kyle").contains(customer.getName()); } }); assertTrue(linkedList1.size() == 2); }
Podemos usar select y selectRejected si queremos que se devuelva la lista resultante en lugar de una bandera booleana.
4.5. Comprobación de no vacío
El método isNotEmpty es bastante útil cuando queremos comprobar si hay al menos un elemento en una lista. La otra forma de comprobar lo mismo es:
boolean isNotEmpty = (list != null && list.size() > 0);
Aunque la línea de código anterior hace lo mismo, CollectionUtils.isNotEmpty mantiene nuestro código más limpio:
@Test public void givenNonEmptyList_whenCheckedIsNotEmpty_thenTrue() { assertTrue(CollectionUtils.isNotEmpty(list1)); }
El isEmpty hace lo contrario. Comprueba si la lista dada es nula o si hay cero elementos en la lista:
List emptyList = new ArrayList(); List nullList = null; assertTrue(CollectionUtils.isEmpty(nullList)); assertTrue(CollectionUtils.isEmpty(emptyList));
4.6. Comprobación de inclusión
Podemos usar isSubCollection para verificar si una colección está contenida en otra colección. isSubCollection toma dos colecciones como argumentos y devuelve verdadero si la primera colección es una subcolección de la segunda colección:
@Test public void givenCustomerListAndASubcollection_whenChecked_thenTrue() { assertTrue(CollectionUtils.isSubCollection(list3, list1)); }
A collection is sub-collection of another collection if the number of times an object occurs in the first collection is less than or equal to the number of times it occurs in the second collection.
4.7. Intersection of Collections
We can use CollectionUtils.intersection method to get the intersection of two collections. This method takes two collections and returns a collection of elements of which are common in both the input collections:
@Test public void givenTwoLists_whenIntersected_thenCheckSize() { Collection intersection = CollectionUtils.intersection(list1, list3); assertTrue(intersection.size() == 2); }
The number of times an element occurs in the resultant collection is a minimum of the number of times it occurs in each of the given collections.
4.8. Subtracting Collections
CollectionUtils.subtract takes two collections as input and returns a collection which contains elements which are there in the first collection but not in the second collection:
@Test public void givenTwoLists_whenSubtracted_thenCheckElementNotPresentInA() { Collection result = CollectionUtils.subtract(list1, list3); assertFalse(result.contains(customer1)); }
The number of times a collection occurs in the result is the number of times it occurs in first collection minus the number of times it occurs in the second collection.
4.9. Union of Collections
CollectionUtils.union does the union of two collections and returns a collection which contains all the elements which are there in either the first or the second collection.
@Test public void givenTwoLists_whenUnioned_thenCheckElementPresentInResult() { Collection union = CollectionUtils.union(list1, list2); assertTrue(union.contains(customer1)); assertTrue(union.contains(customer4)); }
The number of times an element occurs in the resulting collection is the maximum of the number of times it occurs in each of the given collections.
5. Conclusion
And we're done.
We went through some of the commonly used methods of CollectionUtils – which is very much useful to avoid boilerplate when we're working with collections in our Java projects.
As usual, the code is available over on GitHub.
Siguiente » Colecciones de Apache Commons MapUtils « Anterior Colecciones de Apache Commons BidiMap