Java Tutorial
🔍
Java ProgramsCollectionsArrayList Basics

ArrayList Basics in Java

beginner·  Collections  ·  List

Problem

ArrayList is a resizable list implementation that lets you add, remove, and access elements by index.

Add elements to an ArrayList, remove one, and print what remains.

Java Program

Java
import java.util.ArrayList; public class ArrayListDemo { public static void main(String[] args) { ArrayList<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); fruits.remove("Banana"); // removes by value, not by index for (String fruit : fruits) { System.out.println(fruit); } } }

Output

Apple Cherry

Core Logic

ArrayList makes this easy — add a few elements, remove one by value, and loop over what's left.

How It Works
  1. 1new ArrayList<String>() creates an empty, resizable list.
  2. 2add() appends each new element to the end of the list.
  3. 3remove("Banana") searches for the first matching element and deletes it, shifting later elements down by one index.
  4. 4The enhanced for-loop walks the remaining elements in their current order.
After adding Apple, Banana, and Cherry, then removing Banana, the loop prints Apple and Cherry.
💡

Key Point: remove() here takes the object value, not an index — remove(1) would instead delete by position.

Key Concepts

ArrayListadd()remove()

Approach 2: removeIf() with a Lambda

Java
import java.util.ArrayList; public class ArrayListDemoRemoveIf { public static void main(String[] args) { ArrayList<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); // Removes every element matching the lambda condition fruits.removeIf(fruit -> fruit.equals("Banana")); for (String fruit : fruits) { System.out.println(fruit); } } }

Output

Apple Cherry

Core Logic

removeIf() offers a different way to delete — hand it a lambda condition instead of an exact value to match.

How It Works
  1. 1fruits.removeIf(fruit -> fruit.equals("Banana")) takes a Predicate<String> — a lambda that returns true for elements to remove.
  2. 2Internally, removeIf() walks the list and deletes every element the predicate matches, which can be more than one.
  3. 3The rest of the program — building the list with add() and printing with a for-each loop — stays the same.
removeIf(fruit -> fruit.equals("Banana")) removes "Banana", leaving Apple and Cherry, same as the direct remove("Banana") call.
💡

Key Point: Unlike remove(Object), which deletes only the first match, removeIf() removes every element matching the condition — useful when a value might appear more than once in the list.

Key Concepts

removeIf()Predicatelambda expression

Related Programs