I have a class in that I take one list of generic type. Now I am trying to iterate over that list to get the value of that class. In getOrderAmount() method I trying to iterate.
#Document(collection = Cart.FIELDS.COLLECTION)
public class Cart extends BaseOrderEntity {
public interface FIELDS extends BaseOrderEntity.FIELDS {
String COLLECTION = "cart";
String LIST_ORDERS = "orderList";
String CART_TYPE = "cartType";
}
#Field(value = FIELDS.LIST_ORDERS)
private List<T> orderList;
#Field(value = FIELDS.CART_TYPE)
private Integer cartType;
public List<T> getOrderList() {
return orderList;
}
public void setOrderList(List<T> orderList) {
this.orderList = orderList;
}
public Integer getCartType() {
return cartType;
}
public void setCartType(Integer cartType) {
this.cartType = cartType;
}
#Override
public RefCollectionType getRefCollectionType() {
if (T.class.getClass() == FoodItemOrderDetails.class.getClass()) {
return RefCollectionType.FOOD;
} else if (T.class.getClass() == LaundryItemOrderDetails.class.getClass()) {
return RefCollectionType.LAUNDRY;
} else if (T.class.getClass() == HousekeepingItemOrderDetails.class.getClass()) {
return RefCollectionType.HOUSEKEEPING;
}
return RefCollectionType.FOOD;
}
#Override
public double getOrderAmount() {
double totalfoodOrderAmount = 0.0;
for (FoodItemOrderDetails foodItem : orderList) {
totalfoodOrderAmount = totalfoodOrderAmount + (foodItem.getPrice() * foodItem.getQuantity());
}
return totalfoodOrderAmount;
}
}
The generic classes are here.
FoodItemOrderDetails
LaundryItemOrderDetails
HousekeepingItemOrderDetails
You should have an interface like OrderDetails which should have 2 methods getQuantity() and getPrice(). Now implement that interface in FoodItemOrderDetails,
LaundryItemOrderDetails, HousekeepingItemOrderDetails.
for (OrderDetails item : orderList) {
totalAmount = totalAmount + (item .getPrice() * item.getQuantity());
}
Your Interface should looks like below.
interface OrderDetails {
Double getPrice();
Integer getQuantity();
}
Your classes should look like below.
class FoodItemOrderDetails implements OrderDetails {
#Override
public Double getPrice() {
// return the price for FoodItem
return null;
}
#Override
public Integer getQuantity() {
// return the Quantity for FoodItem
return null;
}
}
You can use Java-8 stream.
List<OrderDetails> details = new ArrayList<>();
double total = details.stream().mapToDouble(e -> e.getPrice() * e.getQuantity()).sum();
Related
EDITED to clarify further.
I'm trying to build a simple api which handles the CRUD operation on my simple MySQL database for my simple Ordering Web App. The api will then be used on Angular.
Basically, the conditions for the ordering system is that there would be a 5% off on selected orders, so that would be DiscountedBill job to calculate on how much it would be. Other items do not have the discount, so that would be for RegularBill job to calculate.
As I have understood on this diagram, OrderBill class will have to calculate on how much the TOTAL of ALL orders if the user has DiscountedBill and RegularBill orders on my system.
Would that be possible?
This is the main OrderBill class.
public class OrderBill {
private List<Order> orderList;
private CafeClerk clerk;
public OrderBill(CafeClerk clerk) {
this.clerk = clerk;
}
public List<Order> getOrderList() {
return orderList;
}
public void setOrderList(List<Order> orderList) {
this.orderList = orderList;
}
public CafeClerk getClerk() {
return clerk;
}
public void setClerk(CafeClerk clerk) {
this.clerk = clerk;
}
public double getTotalBill() {
// function here to add the computed data of both DiscountedBill + RegularBill
return 0;
}
}
RegularBill class –
public class RegularBill extends OrderBill {
public RegularBill(CafeClerk clerk) {
super(clerk);
}
double totalRegBill = 0.0;
#Override
public double getTotalBill() {
for (Order order : super.getOrderList()) {
totalRegBill += (order.getPrice());
}
return totalRegBill;
}
public double getTotalRegBill() {
return totalRegBill;
}
public void setTotalRegBill(double totalRegBill) {
this.totalRegBill = totalRegBill;
}
}
DiscountedBill class –
public class DiscountedBill extends OrderBill {
public DiscountedBill(CafeClerk clerk) {
super(clerk);
}
final double DISCOUNT = 0.05;
double totalDiscBill = 0.0;
#Override
public double getTotalBill() {
for (Order order :super.getOrderList()) {
totalDiscBill += (order.getPrice() - DISCOUNT);
}
return totalDiscBill;
}
public double getTotalDiscBill() {
return totalDiscBill;
}
public void setTotalDiscBill(double totalDiscBill) {
this.totalDiscBill = totalDiscBill;
}
}
I am not sure if I understand the purpose correctly, but if you want to sum up the DiscountedBill and RegularBill in OrderBill, don't you rather need a structure like this?
public class OrderBill {
private List<Order> orderList;
private CafeClerk clerk;
private RegularBill regularBill;
private DiscountedBill discountedBill;
public OrderBill(CafeClerk clerk) {
this.clerk = clerk;
}
public List<Order> getOrderList() {
return orderList;
}
public void setOrderList(List<Order> orderList) {
this.orderList = orderList;
}
public CafeClerk getClerk() {
return clerk;
}
public void setClerk(CafeClerk clerk) {
this.clerk = clerk;
}
public double getTotalBill() {
return regularBill.getTotalBill(orderList) + discountedBill.getTotalBill(orderList);
}
}
public class RegularBill {
public RegularBill() {}
double totalRegBill = 0.0;
public double getTotalBill(List<Order> orders) {
for (Order order : orders) {
totalRegBill += (order.getPrice());
}
return totalRegBill;
}
public double getTotalRegBill() {
return totalRegBill;
}
public void setTotalRegBill(double totalRegBill) {
this.totalRegBill = totalRegBill;
}
}
public class DiscountedBill {
public DiscountedBill() { }
final double DISCOUNT = 0.05;
double totalDiscBill = 0.0;
public double getTotalBill(List<Order> orders) {
for (Order order : orders) {
totalDiscBill += (order.getPrice() - DISCOUNT);
}
return totalDiscBill;
}
public double getTotalDiscBill() {
return totalDiscBill;
}
public void setTotalDiscBill(double totalDiscBill) {
this.totalDiscBill = totalDiscBill;
}
}
Of course, enhancing this solution is necessary. But that may be a hint already.
You can then implement an interface with getTotalBill() method.
If you need to recreate this diagram, then my hint is that you make OrderBill abstract, and getTotalBill() interests you only in the RegularBill and DiscountedBill.
You cannot really add up these two classes inside of OrderBill with the given structure.
If I understand that right, you could do:
public DiscountedBill(RegularBill bill) {
this.setOrderList(bill.getOrderList);
this.setClerk(bill.getClerk());
}
#Override
public double getTotalBill() {
for (Order order :this.getOrderList()) {
totalDiscBill += (order.getPrice() - DISCOUNT);
}
return totalDiscBill;
}
Notice: If I get it right, you are just subtracting 0.05 in total not in %, mabbe it should be:
#Override
public double getTotalBill() {
for (Order order :this.getOrderList()) {
totalDiscBill += (order.getPrice() - (order.getPrice() * DISCOUNT));
}
return totalDiscBill;
}
But it is just a guess what I think what you trying to archieve.
I would appreciate any help in solving the following question.
Design and implement a subclass of GenericOrder called ComputerPartyOrder that takes an arbitrary number of different classes of ComputerPart objects, Peripheral objects, Cheese objects, Fruit objects and Service objects.
here is the code for Product class and GerericOrder class.
abstract class Product {
protected float price;
// return the price of a particular product
abstract float price();
//public getType() {
//
//}
}
//------------------------------------------------------------
class ComputerPart extends Product {
public ComputerPart(float p) {
price = p;
}
public float price() { return price; }
}
class Motherboard extends ComputerPart {
protected String manufacturer;
public Motherboard(String mfg, float p) {
super(p);
manufacturer = mfg;
}
public String getManufacturer() { return manufacturer; }
}
class RAM extends ComputerPart {
protected int size;
protected String manufacturer;
public RAM(String mfg, int size, float p) {
super(p);
this.manufacturer = mfg;
this.size = size;
}
public String getManufacturer() { return manufacturer; }
}
class Drive extends ComputerPart {
protected String type;
protected int speed;
public Drive(String type, int speed, float p) {
super(p);
this.type = type;
this.speed = speed;
}
public String getType() { return type; }
public int getSpeed() { return speed; }
}
class Peripheral extends Product {
public Peripheral(float p) {
price = p;
}
public float price() { return price; }
}
class Printer extends Peripheral {
protected String model;
public Printer(String model, float p) {
super(p);
this.model = model;
}
public String getModel() { return model; }
}
class Monitor extends Peripheral {
protected String model;
public Monitor(String model, float p) {
super(p);
this.model = model;
}
public String getModel() { return model; }
}
class Service extends Product {
public Service(float p) {
price = p;
}
public float price() { return price; }
}
class AssemblyService extends Service {
String provider;
public AssemblyService(String pv, float p) {
super(p);
provider = pv;
}
public String getProvider() { return provider; }
}
class DeliveryService extends Service {
String courier;
public DeliveryService(String c, float p) {
super(p);
courier = c;
}
public String getCourier() { return courier; }
}
//-------------------------------------------------------
class Cheese extends Product {
public Cheese(float p) {
price = p;
}
public float price() { return price; }
}
class Cheddar extends Cheese {
public Cheddar(float p) {
super(p);
}
}
class Mozzarella extends Cheese {
public Mozzarella(float p) {
super(p);
}
}
class Fruit extends Product {
public Fruit(float p) {
price = p;
}
public float price() { return price; }
}
class Apple extends Fruit {
public Apple(float p) {
super(p);
}
}
class Orange extends Fruit {
public Orange(float p) {
super(p);
}
}
GenericOrder:
import java.util.ArrayList;
import java.util.List;
public abstract class GenericOrder<T> extends Product {
private static long counter = 1;
private final long id = counter++;
private List<T> Item;
public GenericOrder() {
Item = new ArrayList<T>();
}
public long getid() {
return id;
}
public void addItem(T newItem) {
Item.add(newItem);
}
public List<T> getItem() {
return Item;
}
public void setItem(List<T> Item) {
this.Item = Item;
}
}
EDIT: Code so far
public abstract class ComputerPartyOrder extends GenericOrder {
GenericOrder GOrder = new GenericOrder() {
#Override
float price() {
return 0;
}
};
public void input(Product newitem) {
GOrder.addItem(newitem);
}
public void output() {
System.out.println(GOrder.getItem());
}
}
You have the right idea, but GenericOrder does not need a type parameter T. Instead, you can set the type of Item to Product (the superclass of all the different types of products).
public abstract class GenericOrder extends Product {
private static long counter = 1;
private final long id = counter++;
private List<Product> Item;
public GenericOrder() {
Item = new ArrayList<Product>();
}
public long getid() {
return id;
}
public void addItem(Product newItem) {
Item.add(newItem);
}
public List<Product> getItem() {
return Item;
}
public void setItem(List<Product> Item) {
this.Item = Item;
}
}
You will still be able to call addItem with any instance of a subclass of Product.
I would also suggest renaming Item to item, uppercase names are usually used for types, not variables.
I have an assignment to make this Restaurant Program. it Consists of an Order Class a product class and the main class. Order has an ArrayList to hold the products. I create an instance of the Order and then I add items through my main method.A product has a name(string) a bar-code(string), and a price(float).
Then I have to output a receipt.But what if a customer orders more of one product? Do I instantiate everything one by one? Is a second Beer Product independent? Should I hold quantities somehow? If I want to add a second beer I have to create a new product Beer2 etc? I don't know beforehand how many products each order will hold and the quantity of each so Is this way of instantiating proper? Thanks
Note: it is still incomplete as I want to deal with this before I move on.
import java.util.Date;
public class MyRestaurantTester {
public static void main(String[] args) {
Date currentDate = new Date();
Paraggelia order1 = new Paraggelia(currentDate,"11B");
Product Beer = new Product("Amstel","111222",1.20f);
Product Beef = new Product("Pork Beef","333444",8.50f);
order1.add(Beer);
order1.add(Beef);
System.out.println(order1.getReceipt(30f));
}
}
Order Class(nevermind the name Paraggelia I gave it)
import java.util.ArrayList;
import java.util.Date;
/*Notes to self:
* -Work on Comments
* -Javadocs maybe?
* -try to optimize the rough code.
*/
/*Order class*/
public class Paraggelia {
private Date orderDate;
private String tableNumber;
private int customerCount;
private ArrayList<Product> listOfItems;
/*Constructor(s)*/
Paraggelia(Date orderDate,String tableNumber){
this.orderDate=orderDate;
this.tableNumber=tableNumber;
this.listOfItems = new ArrayList<Product>();
}
/*Add && Delete Products from the Order class*/
public void add(Product p){
if(p == null)
{
throw new IllegalArgumentException();
}else{
listOfItems.add(p);
}
}
public void delete(Product p){
if(p == null)
{
throw new IllegalArgumentException();
}
else
{
listOfItems.remove(p);
}
}
/** Calculates and returns the total price
* Usually called directly as a parameter of getReceipt function
* */
public static float getTotalPrice(){
return 0;
}
/** Creates and returns the final Receipt!
* -Display must consist of:
* Item$ - BarCode# - Item Amount#
* Total Price#
* Table Number#
*/
public String getReceipt(float totalPrice){
StringBuilder receipt = new StringBuilder();
for(int i =0; i<this.listOfItems.size();i++){
receipt.append(listOfItems.get(i).getName());
receipt.append("\n");
}
return new String(receipt);
}
/*Getters && Setters */
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public String getTableNumber() {
return tableNumber;
}
public void setTableNumber(String tableNumber) {
this.tableNumber = tableNumber;
}
public int getCustomerCount() {
return customerCount;
}
public void setCustomerCount(int customerCount) {
this.customerCount = customerCount;
}
}
Product Class:
public class Product {
private String Name;
private String barCode;
private float sellingPrice;
/*Constructors: */
Product(){}
Product(String Name,String barCode,float sellingPrice){
this.Name=Name;
this.barCode=barCode;
this.sellingPrice=sellingPrice;
}
/*Getters & Setters*/
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getBarCode() {
return barCode;
}
public void setBarCode(String barCode) {
this.barCode = barCode;
}
public float getSellingPrice() {
return sellingPrice;
}
public void setSellingPrice(float sellingPrice) {
this.sellingPrice = sellingPrice;
}
}
Instead of ArrayList ( List ) you can use Map ( HashMap for example )
MyRestaurantTester
public class MyRestaurantTester {
public static void main(String[] args) {
Date currentDate = new Date();
Paraggelia order1 = new Paraggelia(currentDate,"11B");
Product Beer = new Product("Amstel","111222",1.20f);
Product Beef = new Product("Pork Beef","333444",8.50f);
order1.add(Beer, 1);
order1.add(Beef, 5);
System.out.println(order1.getReceipt(30f));
}
}
Paraggelia
class Paraggelia {
private Date orderDate;
private String tableNumber;
private int customerCount;
private Map<Product, Integer> listOfItems;
/*Constructor(s)*/
Paraggelia(Date orderDate,String tableNumber){
this.orderDate=orderDate;
this.tableNumber=tableNumber;
this.listOfItems = new HashMap<Product, Integer>();
}
/*Add && Delete Products from the Order class*/
public void add(Product p, int quantity){
if(p == null)
{
throw new IllegalArgumentException();
}else{
listOfItems.put(p, quantity);
}
}
public void delete(Product p){
if(p == null)
{
throw new IllegalArgumentException();
}
else
{
listOfItems.remove(p);
}
}
/** Calculates and returns the total price
* Usually called directly as a parameter of getReceipt function
* */
public static float getTotalPrice(){
return 0;
}
/** Creates and returns the final Receipt!
* -Display must consist of:
* Item$ - BarCode# - Item Amount#
* Total Price#
* Table Number#
*/
public String getReceipt(float totalPrice){
StringBuilder receipt = new StringBuilder();
for(Map.Entry<Product,Integer> entry : this.listOfItems.entrySet()) {
Product product = entry.getKey();
Integer quantity = entry.getValue();
receipt.append(product.getName() + " " + quantity);
receipt.append("\n");
}
return new String(receipt);
}
/*Getters && Setters */
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public String getTableNumber() {
return tableNumber;
}
public void setTableNumber(String tableNumber) {
this.tableNumber = tableNumber;
}
public int getCustomerCount() {
return customerCount;
}
public void setCustomerCount(int customerCount) {
this.customerCount = customerCount;
}
}
OUTPUT:
Pork Beef 5
Amstel 1
Three basic approaches come to mind:
Instantiate each product individually
Instead of ArrayList, have another structure that can associate items with quantities; or,
Make a class Article, which belongs to a Product: Product beerProduct = new Product("beer", "0129", 1.37); Article beer = new Article(beerProduct), beer2 = new Article(beerProduct).
The first solution gives you a lot of flexibility (e.g. to discount individual articles for, say, being damaged). The second solution is more economical with objects. The third one captures the intuition that all the Heineken bottles are the same. It is really up to what you want to do - both approaches are equally valid, for some purpose.
I am working in an android application I want to sort a List of Objects with an Object Property. I have sorted it successfully but when I sort it all the List with that object changes the value to same as the sorted value
Please look into ma code :
SortedSet<Caseload> removeDuplicateClientName = new TreeSet<Caseload>(
new Comparator<Caseload>() {
#Override
public int compare(Caseload caseload0, Caseload caseload1) {
return caseload0.ClientName.compareTo(caseload1.ClientName);
}
});
// Getting the list of values from web service
mLISTCaseloadsHeads = parsedXML.getCaseLoadValues("get_Caseload_ClientServiceGroupID", param);
List<Caseload> newBackUp=mLISTCaseloadsHeads ;
Iterator<Caseload> iterator = mCaseloadsHeads.iterator();
while (iterator.hasNext()) {
removeDuplicateClientName.add(iterator.next());
}
mCaseloadsHeads.clear();
mCaseloadsHeads.addAll(removeDuplicateClientName);
The List newBackUp also changes the value to the same as sorted List
Caseload class:
public class Caseload implements Comparable<Caseload> {
public int BusClientLogID;
public int ClientID;
public int ClientStatus;
public int ClientServiceGroup_ClientSiteTherapyID;
public String ClientName;
public String TimeArrive;
public String TimeDepart;
public String SignOutTime;
public String SignInTime;
public String ServiceCompletedCount;
public Boolean ShowFooter = false;
public int getBusClientLogID() {
return BusClientLogID;
}
public void setBusClientLogID(int busClientLogID) {
BusClientLogID = busClientLogID;
}
public int getClientID() {
return ClientID;
}
public void setClientID(int clientID) {
ClientID = clientID;
}
public int getClientStatus() {
return ClientStatus;
}
public void setClientStatus(int clientStatus) {
ClientStatus = clientStatus;
}
public int getClientServiceGroup_ClientSiteTherapyID() {
return ClientServiceGroup_ClientSiteTherapyID;
}
public void setClientServiceGroup_ClientSiteTherapyID(
int clientServiceGroup_ClientSiteTherapyID) {
ClientServiceGroup_ClientSiteTherapyID = clientServiceGroup_ClientSiteTherapyID;
}
public String getClientName() {
return ClientName;
}
public void setClientName(String clientName) {
ClientName = clientName;
}
public String getTimeArrive() {
return TimeArrive;
}
public void setTimeArrive(String timeArrive) {
TimeArrive = timeArrive;
}
public String getTimeDepart() {
return TimeDepart;
}
public void setTimeDepart(String timeDepart) {
TimeDepart = timeDepart;
}
public String getSignOutTime() {
return SignOutTime;
}
public void setSignOutTime(String signOutTime) {
SignOutTime = signOutTime;
}
public String getSignInTime() {
return SignInTime;
}
public void setSignInTime(String signInTime) {
SignInTime = signInTime;
}
public String getServiceCompletedCount() {
return ServiceCompletedCount;
}
public void setServiceCompletedCount(String serviceCompletedCount) {
ServiceCompletedCount = serviceCompletedCount;
}
#Override
public int compareTo(Caseload compareCaseload) {
int busClientLogID = ((Caseload) compareCaseload).getBusClientLogID();
return busClientLogID - this.BusClientLogID;
}
}
Please give me a solution.
I doubt the return statement associated with your compare function in the comparator.
You should go by this approach to get the right ordering :
#Override
public int compare(YourClass lhs, YourClass rhs) {
YourClass p1 = (YourClass) lhs;
YourClass p2 = (YourClass) rhs;
int first = p1.ClientName; //use your getter if you want
int second = p2.ClientName;
if (second < first) {
return 1;
}
else if (second > first) {
return -1;
}
else {
return 0;
}
}
If you go by this approach I guess you will get the required ordering after sort.
Edit:
Now I have got the issue, you are using a reference of the original list in newBackup and its not a new list that is why this is happening, use this and you are good to go.
List<Caseload> newBackUp=new ArrayList<Caseload>(mLISTCaseloadsHeads);
I'm not sure how to address this question. Here is my code:
public interface Stuff {
public String description();
public double weight();
}
class Bag implements Stuff {
public String description() {
return "bag of";
}
public double weight() {
return 10.50;
}
}
class StuffWrapper implements Stuff {
Stuff item;
public StuffWrapper(Stuff item) {
this.item = item;
}
public String description() {
return item.description();
}
public double weight() {
return item.weight();
}
}
class Material extends StuffWrapper {
String material;
double weight;
public Material(Stuff item, String material, double weight) {
super(item);
this.material = material;
this.weight = weight;
}
public String description() {
return item.description() + " :" + material+ ":";
}
public double weight() {
return item.weight() + weight;
}
}
and then I have this:
Stuff icStuff = new Bag();
icStuff = new Material(icStuff, "leather", 10.30);
icStuff = new Material(icStuff, "plastic", 20.50);
System.out.println(icStuff.description() + Double.toString(icStuff.weight()));
which outputs
bag of :leather: :plastic:41.3
After doing all of that if I wanted icStuff to no longer reference this:
icStuff = new Material(icStuff, "plastic", 20.50);
How should I do it?
assign it to something else, or null, or whatever you want it to reference
icStuff = null;
icStuff = Somethingelse;