So I have this ArrayList of Product objects. What I'm doing is on click of + button, I am making an object of Product and setting all the attributes from ui; including 'quantity' and adding this object to ArrayList. Now, as I'm adding a single object on single click of + button, I'm getting duplicate Product objects with all same attributes other than, of course, 'quantity' count. If I add a product with quantity of 4, I get 4 objects of Product inside arraylist with different quantity 1,2,3 and 4. I only want to have Product object with maximum quantity inside the collection. I have used Comparator for this problem, but I am doing something wrong here. Please help find out what I'm doing wrong. Thanks. Here's the model of Product with getter and setters excluded from snippet.
Product:
private String category;
private String code;
private String description;
private String units;
private String weight;
private Integer tax;
private String pieces;
private Integer aliasFlag;
private Double price;
private Integer quantity;
private Integer taxAmount;
private Double totalAmount;
What I'm doing so far to compare two or more(as per the quantity count) objects of Product using Comparator is:
Collections.sort(mProductsToBeSent, new Comparator<Products>() {
@Override
public int compare(Products ob1, Products ob2) {
if (ob1.getCode().equals(ob2.getCode())) {
if (ob1.getQuantity()<ob2.getQuantity()){
mProductsToBeSent.remove(ob1);
}
}
return 0;
}
});
mProductToBeSent is my ArrayList that I'm gonna have to send as a Json, but since there is duplication, this won't do. I'm comparing 'Code' attribute of two subsequent objects for the same product and if it's true then I'm comparing the 'Quantity'. If it's true then I'm removing the lesser quantity object from the list. But I'm not getting desired output.
The output I'm getting right now:
[
Products{Aliasflag='0', Code ='BMA10K', Description=abc, Price=270.0, Quantity=1, Taxamount=0, Units='BAGS'},
Products{Aliasflag='0', Code ='BMA10K', Description=def, Price=270.0, Quantity=2, Taxamount=0, Units='BAGS'},
Products{Aliasflag='0', Code ='BMA10K', Description=ghi, Price=270.0, Quantity=3, Taxamount=0, Units='BAGS'},
Products{Aliasflag='0', Code ='BMA10K', Description=jkl, Price=270.0, Quantity=4, Taxamount=0, Units='BAGS'}
]
As you can see, I'm trying to remove the first three objects to be deleted and only preserve the object with max quantity in the arraylist; that is 4th object--in this case.
Desired output :
[
Products{Aliasflag='0', Code ='BMA10K', Description=jkl, Price=270.0, Quantity=4, Taxamount=0, Units='BAGS'}
]
The usual way to do this is not to add a different product into your list with just another quantity value, but to get the product out of the list and update its quantity.
Wrote as answer because I cannot just comment and I think it will help you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With