Remove empty arraylist from list

In this example we will show how remove empty ArrayList from a list. In the first snippet of java code, we create a list with mock data then use an Iterator to loop over the list and remove empty instances. In the second snippet using java 8, the removeIf is used passing in a predicate that checks if the list is empty. Another way to perform the same operation is to convert the collection to a stream and filter empty elements.

Straight up Java

@Test
public void remove_empty_lists_java() {

    List<List<String>> removeAllEmpty = Lists.newArrayList();
    removeAllEmpty.add(Arrays.asList("abc", "def"));
    removeAllEmpty.add(Arrays.asList("ghi"));
    removeAllEmpty.add(Arrays.asList());

    for (Iterator<List<String>> it = removeAllEmpty.iterator(); it
            .hasNext();) {
        List<String> elem = it.next();
        if (elem.isEmpty()) {
            it.remove();
        }
    }
    assertEquals(2, removeAllEmpty.size());
}

Java 8

@Test
public void remove_empty_lists_java8() {

    List<List<String>> removeEmpty = Lists.newArrayList();
    removeEmpty.add(Arrays.asList("abc", "def"));
    removeEmpty.add(Arrays.asList("ghi"));
    removeEmpty.add(Arrays.asList());

    removeEmpty.removeIf(e -> e.isEmpty());

    assertEquals(2, removeEmpty.size());
}