Skip to content

How to search in arrayList then change?

So i’m making a supermarket program that allows to add products and sell them, so far i have this:

class Product
    String name;
    double price;
    int day;
    int month;
    int year;
    int stock;
    public Product(String name,double price,int day,int month,int year,int stock)

class SuperMarket{
    protected String name;
    protected int numMax;
    private List<Product> pr;
    public SuperMarket(String name,int numMax)
        this.numMax=numMax; = new ArrayList<Product>();
    public void addProduct() {
       //deleted to post here
    public void sellProduct()//its here i need help
        Scanner sc=new Scanner(;
        System.out.println("What product do you want to sell?");
        String name=sc.nextLine();

I´d like to know how to search in Product list by name and then change the stock(subtract-n) to sell n of that product.


You can use Stream API to find out the product by name. Filter the list by checking the name of product and get first match.

Optional<Product> product =
                                       .filter(e ->

Then can check is product found then update the stock

   Product p = product.get();
   p.stock = p.stock - numberOfSoldProduct;

Suggestion to use getter/setter for fields.