Skip to content
Advertisement

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)
    {
        this.name=name;
        this.price=price;
        this.day=day;
        this.month=month;
        this.year=year;
        this.stock=stock;
    }
}

class SuperMarket{
    protected String name;
    protected int numMax;
    private List<Product> pr;
    
    public SuperMarket(String name,int numMax)
    {
        this.name=name;
        this.numMax=numMax;
        this.pr = new ArrayList<Product>();
        
    }
    public void addProduct() {
       //deleted to post here
    }
    
    public void sellProduct()//its here i need help
    {
        Scanner sc=new Scanner(System.in);
        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.

Advertisement

Answer

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 = productList.stream()
                                       .filter(e -> e.name.equals(inputedName))
                                       .findFirst();

Then can check is product found then update the stock

if(product.isPresent()){
   Product p = product.get();
   p.stock = p.stock - numberOfSoldProduct;
}

Suggestion to use getter/setter for fields.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement