Remove element from list

This example will show how to remove element an element from an array list while using java and java 8.

Straight up Java

This snippet below will remove the first occurrence of the specified element from this arraylist calling Lists.remove.

@Test
public void remove_element_from_array_to_arraylist () {
    
    String[] daysOfWeek = {"Sunday", "Monday", "Tuesday", "Wednesday", 
            "Thursday", "Friday", "Saturday"};
    
    List<String> daysOfWeekAsList = Lists.newArrayList(daysOfWeek);
    daysOfWeekAsList.remove("Monday");
    
    logger.info(daysOfWeek);
    
    assertTrue(daysOfWeekAsList.size() == 6);
}

Output

[Sunday, Tuesday, Wednesday, Thursday, Friday, Saturday]

Java 8

This snippet will show how to remove an element from arraylist using java 8. We will pass a java 8 predicate created from a lambda expression to List.removeIf. It will remove each occurrence where the string equals 'Monday' from the collection and return true if an element has been removed.

@Test
public void remove_element_from_array_to_arraylist_java8 () {
    
    String[] daysOfWeek = {"Sunday", "Monday", "Tuesday", "Wednesday", 
            "Thursday", "Friday", "Saturday"};

    
    List<String> daysOfWeekAsList = Lists.newArrayList(daysOfWeek);

    boolean removed = daysOfWeekAsList.removeIf(p -> p.equalsIgnoreCase("Monday"));
    
    logger.info(daysOfWeekAsList);

    assertTrue(removed);
    assertTrue(daysOfWeekAsList.size() == 6);
}    

Output

[Sunday, Tuesday, Wednesday, Thursday, Friday, Saturday]