Start learning free

LESSON 112 OF 671 · ARRAYS I

Checking an ArrayList for a Value in Java

Lesson

TL ; DR:

list.contains(x) is true when the list holds x, and false when it doesn't. Use it as the condition of an if.


List<String> colors = new ArrayList<>(List.of("red", "green", "blue"));

System.out.println(colors.contains("red"));    // true

System.out.println(colors.contains("pink"));   // false

if (!colors.contains("pink")) {
    System.out.println("No pink yet");
}


Full lesson:

Often you need to know if a list holds some value. Is this name on the guest list? Is this item in the cart?

contains(x) answers that. It compares each item with x, from the first one on. It returns true as soon as one matches, or false if none does.

Put ! in front for the opposite. So !colors.contains(x) is true when x is missing.

The answer is a boolean, so it fits right into an if:

List<String> cart = new ArrayList<>(List.of("milk", "bread"));

if (cart.contains("milk")) {
    System.out.println("Milk is in the cart");
}

contains accepts a value of any type. So colors.contains(5) compiles, but it is always false on a list of strings.

Text must match exactly. So colors.contains("Red") is false, because the list has "red".


Your task

bag holds what is packed for a hike.

If "water" is in bag, print Water is packed. If "tent" is not in bag, print Pack a tent.

Expected output:

Water is packed
Pack a tent
STEP 1 OF 2
    Ctrl + Enter to check