Library contents

Java List.contains

Test whether at least one item has the target price.

A simple example

List.contains

  1. Start with 1, 2, 3
  2. Do this Look for 2
  3. Result Found
The requested value matches the second element.

Syntax

Java syntax
prices.contains(3)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Check for a price in a sale list

A retailer checks a list of prices for a particular offer. Decide whether the question requires the presence of the price, its position or the number of occurrences before interpreting the result.

Resultyes
Main.java

class Main {
    public static void main(String[] args) throws Exception {
        var prices = java.util.List.of(8, 3, 12, 3);
        System.out.println((prices.contains(3)) ? "yes" : "no");
    }
}
Output
yes

Two prices are three, so a membership check succeeds. Only one match is required.

Advertisements

Check an invitation before printing a badge

A community center prepares badges only for registered guests. The clerk checks the exact spelling on the guest list and prints a badge when the requested name is already present.

From the programvar invited = List.of("Mira", "Nia")
ResultPrint badge
Main.java
import java.util.List;

class Main {
    public static void main(String[] args) throws Exception {
        var invited = List.of("Mira", "Nia");
        System.out.println(invited.contains("Nia") ? "Print badge" : "Check registration");
    }
}
Output
Print badge

String equality finds Nia in the list and the badge can be printed.

Check a badge at equipment pickup

The media desk releases cameras to students whose badge number is on the pickup list. Badge 204 is on the sheet between 101 and 305. The volunteer must match a whole number before handing out a camera.

GivenBadge 204 · pickup list 101, 204, 305
ResultRelease camera
Main.java
import java.util.List;

class Main {
    public static void main(String[] args) throws Exception {
        var badges = List.of(101, 204, 305);
        System.out.println(badges.contains(204) ? "Release camera" : "Check roster");
    }
}
Output
Release camera

The list contains badge 204, so the volunteer can release the camera. The recorded numbers identify students individually.

What to watch for

Membership answers a yes-or-no question. Use a count when you need the number of matches.

Documentation for List.contains