Optimize uniqueness check

Optimize the generation of unique identifiers.

You can query a model directly and test the results returned when using different parameter values with the Cloud console, or by calling the Vertex AI API directly.

System instructions

You are a coding chatbot that is not conversational with the user. You provide a short, level-2 heading about the main solution and then you give the main solution concisely.

Prompt Freeform

This is my Java code to add products to my inventory. My team lead told me that the code is not efficient and that I'll start running into trouble when the number of products gets higher. Can you suggest one way I can fix the code to avoid this and fully implement that change within the code?

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class ProductInventory {

private static final List<Product> products = new ArrayList<>();
private static final Random random = new Random();

public static void main(String[] args) {

addProduct("Product1");
addProduct("Product2");
addProduct("Product3");

System.out.println("All Products:");
for (Product product : products) {
System.out.println("Name: " + product.getName() + ", ID: " + product.getId());
}
}

public static void addProduct(String productName) {
String randomId;
boolean idIsUnique;
long startTime;
long endTime;
long duration;

// Record start time
startTime = System.nanoTime();

do {
randomId = getRandomId();
idIsUnique = true;

for (Product product : products) {
if (product.getId().equals(randomId)) {
idIsUnique = false;
System.out.println("ID " + randomId + " already exists. Generating a new ID.");
break;
}
}
} while (!idIsUnique);

products.add(new Product(productName, randomId));
System.out.println("Added " + productName + " with ID: " + randomId);

// Record end time and calculate duration
endTime = System.nanoTime();
duration = endTime - startTime;
System.out.println("Time taken to add " + productName + ": " + duration + " nanoseconds");
}

public static String getRandomId() {
return "ID" + random.nextInt(1000);
}
}

// Product class to store product name and ID
class Product {
private final String name;
private final String id;

public Product(String name, String id) {
this.name = name;
this.id = id;
}

public String getName() {
return name;
}

public String getId() {
return id;
}
}

Response

Use a HashSet for Efficient ID Lookups

To improve performance, you can use a HashSet to store existing product IDs. A HashSet provides average O(1) or constant-time complexity for checking if an ID exists, which is much more efficient than iterating through the entire ArrayList (O(n) complexity) for each new product.

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

public class ProductInventory {

    private static final List<Product> products = new ArrayList<>();
    // Use a HashSet for fast, O(1) average time complexity lookups.
    private static final Set<String> productIds = new HashSet<>();
    private static final Random random = new Random();

    public static void main(String[] args) {

        addProduct("Product1");
        addProduct("Product2");
        addProduct("Product3");

        System.out.println("All Products:");
        for (Product product : products) {
            System.out.println("Name: " + product.getName() + ", ID: " + product.getId());
        }
    }

    public static void addProduct(String productName) {
        String randomId;
        long startTime;
        long endTime;
        long duration;

        // Record start time
        startTime = System.nanoTime();

        // Generate a unique ID by checking against the HashSet
        do {
            randomId = getRandomId();
            if (productIds.contains(randomId)) {
                System.out.println("ID " + randomId + " already exists. Generating a new ID.");
            }
        } while (productIds.contains(randomId));

        // Add the new product to the list and its ID to the set
        products.add(new Product(productName, randomId));
        productIds.add(randomId);

        System.out.println("Added " + productName + " with ID: " + randomId);

        // Record end time and calculate duration
        endTime = System.nanoTime();
        duration = endTime - startTime;
        System.out.println("Time taken to add " + productName + ": " + duration + " nanoseconds");
    }

    public static String getRandomId() {
        return "ID" + random.nextInt(1000);
    }
}

// Product class to store product name and ID
class Product {
    private final String name;
    private final String id;

    public Product(String name, String id) {
        this.name = name;
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public String getId() {
        return id;
    }
}
Model: gemini-2.5-pro
Temperature: 0.2
Max output tokens: 8192
TopK: 40.0
TopP: 0.95