I have a question about hashmap,
I have a class product:
public class product{
private String libele;
and also a class special product:
public class SpecialProd extends Product{
private HashMap<Product, Price> comp = new HashMap<Product, Price>();
public HashMap<Product, Price> getComp() {
return comp;
}
}
The problem is that i need to know how much products i have in stock, the total amount of the products and how much for every product:
so i used this code in the class storage:
public class Storage{
private HashMap<Product, Price> port = new HashMap<Product, Price>();
public void total (){
int nombre=0;
int total = 0;
int i=0;
for (Product p:port.keySet()){
if (port.containsKey(a)){
// ++nombre;
}
total = port.size();
System.out.println(+nombre+ "of" +a.getLibele());
}
System.out.println("total products:" +total);
}
// this is an intern class
static class Part{
private int price;
public Price(int price) {
this.price= price;
}
public int getprice() {
return price;
}
public void setPrice(int price) {
this.price= price;
}
}
}
i couldn't get the count of every product and the total prices.
Any ideas please?
You can try enumerating the HashMap and get the desired values.
int count=0;
for(p : port.keySet()){
count ++;
price = price + port.get(a);
}
Related
I have a number of evaluations I'm looking to make to a collection of data and I've been trying to figure out how to accomplish this with streams. I'm looking at streams specifically because the collection sizes can be fairly large and i'd like to take advantage of the parallel processing.
Here is some sample code, which reflects a basic structure -
import java.math.BigDecimal;
import java.util.Map;
import java.util.List;
public class TestApplication {
/***
* Enumerated list of various product types
***/
public enum ProductType {
TOY, BATH, BEDROOM, OUTDOOR
}
/***
* Represents each product we have in inventory.
***/
class Product {
public String name;
public ProductType type;
public int quantity = 0;
public double costPerUnit = 0;
public double productValue = 0;
public float percentOfTotalInventory;
public void setName(String name) { this.name = name; }
public void setProductType(ProductType type) { this.type = type; }
public void setQuantity(int quantity) { this.quantity = quantity; }
public void setCostPerUnit(double unitCost) { this.costPerUnit = unitCost; }
public void calculateProductValue() {
this.productValue = quantity * costPerUnit;
}
public void calculatePercentageOfTotalInventory(double totalInventoryValue) {
this.percentOfTotalInventory = (float) ((costPerUnit * 100) / totalInventoryValue);
}
public String getName() { return name; }
public ProductType getType() { return type; }
public int getQuantity() { return quantity; }
public double getCostPerUnit() { return costPerUnit; }
public float getPercentOfTotalInventory() { return percentOfTotalInventory; }
}
/***
* summary of all the products in our inventory.
*
* in addition to the catalog of products, will keep a running total cost of
* the current inventory and a summary grouping of the products by type
***/
class ProductInventory {
public List<Product> products;
public BigDecimal totalCostOfInventory;
public Map<ProductType, List<ProductSummaryByType>> productsByType;
public void accept(Product p) {
p.calculateProductValue();
products.add(p);
totalCostOfInventory = totalCostOfInventory.add(BigDecimal.valueOf(p.getCostPerUnit()));
}
public void combine(ProductInventory other) {
this.products.addAll(other.products);
this.totalCostOfInventory = totalCostOfInventory.add(other.totalCostOfInventory);
}
}
private class ProductSummaryByType {
//for a type (toy, bath, bed)
public ProductType Type;
//provide total value of inventory for this product type
public double value;
public float percentageOfTotal;
public void calcPercentOfTotal(double total) {
//given the typeValuation, calculate percentage of the total inventory is this type?
this.percentageOfTotal = (float) ((this.value * 100) / total);
}
}
private Map<String, BigDecimal> getProductPrice(String productName) {
//get current price for product
Map<String, BigDecimal> productInfo = new HashMap<String, BigDecimal>();
//simulate the pricing
productInfo.put(productName, BigDecimal.ONE);
return productInfo;
}
public void run(String... args) throws Exception {
//provide product list and process stream
}
}
For a collection of Products, each Product will have a varying purchase price each day, so there is a different routine to set the costPerUnit.
I'm looking to:
iterate over the list of products and capture a collection of the product names
e.g: List<String> productNames = productList.stream().map(Product::getName).collect(Collectors.toList());
Map the names to a function to get the current price
e.g: productNames.stream().map(this::getProductPrice).collect(Collectors.toList());
For each item in the updated price list, set the costPerUnit for each matching instance in the product inventory collection
For each instance of the product, calculate the cost (calculateProductValue) on each instance and add to the ProductInventory, I assume as a custom collector, so it can calculate the total cost of all inventory
with total cost of all inventory, calculate the percentOfTotalInventory for each product by calling the calculatePercentageOfTotalInventory
lastly, group the inventory by ProductType with the total value for the group (adding the productValue for each instance in the group) and calculate the percentageOfTotal for the group in the ProductSummaryByType class
the ProductInventory class should be fully populated at the end of the chain
Again, the reason for trying to do this with nested logic is because I'd like to invoke with parallelism. If you have any suggestions on how best to accomplish, I could use the guidance.
I have a class of Person with an ArrayList of the class Groceries.
Let's name the Arraylist shoppingBag.
Student and Groceries has one field each, int money and int price.
The specific amount of money and price is up to you when initializing new objects.
So every time a Person adds an object of Groceries to his shoppingBag, the amount of money he has needs to be reduced with the total price of groceries added to the bag.
How do you do that?
So, let my try to understand what you want (as I do the same for my clients)
You have a class Groceries with price field:
class Groceries {
private int price;
public Groceries(int price) {
this.price = price;
}
public int getPrice() {
return price;
}
#Override
public String toString() {
return "Groceries{" +
"price=" + price +
'}';
}
}
And class person with int money filed and shopping bag field as List of Groceries:
class Person {
private List<Groceries> shoppingBag = new ArrayList<>();
private int money;
public Person(int money) {
this.money = money;
}
public List<Groceries> getShoppingBag() {
return shoppingBag;
}
public int getMoney() {
return money;
}
}
Firstly you create an instance of Person with some mount of money: Person person = new Person(150);
And then each time when you add a groceries to the shopping bag, like person.getShoppingBag().add(new Groceries(10)); you do want to reduce amount of money from the person instance.
So, If I am correct, you need to implement several things:
1) You should forbid adding groceries to the shopping bag with the way described before. We need to throw an exception when someone tries to add an element to the List via getter. It can be implemented using an Unmodifiable copy of your list:
public List<Groceries> getShoppingBag() {
List<Groceries> bag = new UnmodifiableArrayList<>(shoppingBag.toArray(new Groceries[shoppingBag.size()]), shoppingBag.size());
return bag;
}
or a little bit nicely and shortly using Guava:
public List<Groceries> getShoppingBag() {
List<Groceries> bag = ImmutableList.copyOf(shoppingBag);
return bag;
}
2) Add a method that will add a groceries directly. You can also throw an exception if there is no enough money to not have negative balance:
public void addToShoppingBag(Groceries groceries) {
if (0 > money - groceries.getPrice()) {
throw new IllegalStateException("You have not enough money!");
}
shoppingBag.add(groceries);
money -= groceries.getPrice();
}
3) Probably you will need to have possibility to add some money:
private void addMoney(int amout) {
money += amout;
}
Please see the completely demo example:
class Demo {
public static void main(String[] args) throws IOException {
Person person = new Person(42);
try {
System.out.println(person.getMoney());
person.addToShoppingBag(new Groceries(12));
person.addToShoppingBag(new Groceries(20));
person.addToShoppingBag(new Groceries(5));
System.out.println(person.getMoney());
System.out.println(person.getShoppingBag());
person.getShoppingBag().add(new Groceries(1));
} catch (UnsupportedOperationException e) {
e.printStackTrace();
}
try {
person.addToShoppingBag(new Groceries(66));
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
}
class Person {
private List<Groceries> shoppingBag = new ArrayList<>();
private int money;
public Person(int money) {
this.money = money;
}
public List<Groceries> getShoppingBag() {
List<Groceries> bag = ImmutableList.copyOf(shoppingBag);
return bag;
}
public void addToShoppingBag(Groceries groceries) {
if (0 > money - groceries.getPrice()) {
throw new IllegalStateException("You have not enough money!");
}
shoppingBag.add(groceries);
money -= groceries.getPrice();
}
private void addMoney(int amout) {
money += amout;
}
public int getMoney() {
return money;
}
}
class Groceries {
private int price;
public Groceries(int price) {
this.price = price;
}
public int getPrice() {
return price;
}
#Override
public String toString() {
return "Groceries{" +
"price=" + price +
'}';
}
}
PS: Please next time describe some examples of code and demos to get an answer :)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am having this error where it prints out just the last element entered, prints out it the same amount of times as there are elements that are supposed to be in the array.
I have tested it with a System.out.println and the elements that are being added appear to be correct. How do I fix this error?
package stock.control.system;
import java.util.*;
public class StockArrayList implements StockList {
private ArrayList<StockItem> StockItems;
private int index = 0;
private int update;
private int counter = 0;
public StockArrayList() {
StockItems = new ArrayList<StockItem>(counter);
}
#Override
public void addItem(StockItem item) {
StockItem aItem = new StockItem(StockItem.getItemID(),
StockItem.getItemDesc(),
StockItem.getPrice(),
StockItem.getQuantity(),
StockItem.getReOrderLevel());
StockItems.add(counter, aItem);
counter++;
}
#Override
public String formatStockList(){
String temp = StockItem.format();
for (StockItem items : StockItems) {
temp = temp + items.arrayFormat() + "\n";
}
return temp;
}
}
The main method:
public class StockArrayListTester {
public static void main(String[] args) {
StockArrayList Stock = new StockArrayList();
Stock.addItem(new StockItem("P123","1TB Hard drive",75.00,267,50));
Stock.addItem(new StockItem("P125","i7 6800HQ Processor",257.00,113,45));
Stock.addItem(new StockItem("P129","i5 500HQ Processor",127.00,10,45));
Stock.deleteItem("P129");
System.out.printf(Stock.formatStockList());
}
}
the stock item class
package stock.control.system;
import java.util.*;
public class StockItem {
private static String itemID; // Five alpha-numeric characters
private static String itemDesc; // Item description
private static double price; // Item price in pounds sterling
private static int quantity; // Quantity in stock
private static int reOrderLevel; // Level at which to re-order
public StockItem(String itemID, String itemDesc, double price, int quantity, int reOrderLevel) {
this.itemID = itemID;
this.itemDesc = itemDesc;
this.price = price;
this.quantity = quantity;
this.reOrderLevel = reOrderLevel;
}
#Override
public String toString() {
String toString ="[Item ID = " + this.itemID + ", Item Description = " +
this.itemDesc + ", Price = " + this.price + ", Quantity = " +
this.quantity + ", Re Order Level = " + this.reOrderLevel + "]";
return toString;
}
public static String format() {
String format = " STOCK ITEMS"
+ String.format("\n%-10s%-30s%-10s%-12s%-14s%-10s%-30s%-10s%-12s%-14s\n",
"ItemID","Item Description",
"Price","Quantity", "Re Order Level", "\n******",
" ****************"," *****", " ********",
" **************");
return format;
}
public String arrayFormat() {
return String.format("%-10s%-30s%-10s%-12s%-14s",
StockItem.getItemID(),
StockItem.getItemDesc(),
StockItem.getPrice(),
StockItem.getQuantity(),
StockItem.getReOrderLevel());
}
public static String getItemID(){
return itemID;
}
public static String getItemDesc() {
return itemDesc;
}
public static double getPrice() {
return price;
}
public double setPrice(double price) {
this.price = price;
return price;
}
public static int getQuantity() {
return quantity;
}
public int setQuantity(int quantity) {
this.quantity = quantity;
return quantity;
}
public static int getReOrderLevel(){
return reOrderLevel;
}
public int setReOrderLevel(int reOrderLevel){
this.reOrderLevel = reOrderLevel;
return reOrderLevel;
}
}
The output I get is:
STOCK ITEMS
ItemID Item Description Price Quantity Re Order
P129 i5 500HQ Processor 127.0 10 45
P129 i5 500HQ Processor 127.0 10 45
P129 i5 500HQ Processor 127.0 10 45
BUILD SUCCESSFUL (total time: 0 seconds)
As a rule, never set static fields in a constructor. It is almost certainly a bug. IMHO, this should be a compiler error but it's not.
In this case, you are expecting each instance of StockItem to be different, however by making the fields static you are ensuring there is only one copy, only one value for those fields. I suggest you make them instance fields.
public class StockItem {
private final String itemID; // Five alpha-numeric characters
private final String itemDesc; // Item description
private double price; // Item price in pounds sterling
private int quantity; // Quantity in stock
private int reOrderLevel; // Level at which to re-order
public StockItem(String itemID, String itemDesc, double price, int quantity, int reOrderLevel) {
this.itemID = itemID;
this.itemDesc = itemDesc;
this.price = price;
this.quantity = quantity;
this.reOrderLevel = reOrderLevel;
}
It's been a little while since I've used Java but it seems weird that in your addItem() method in your StockList class that you pass in a parameter 'item' but then never use it inside the method.
Why are you trying to "get" all of the properties of the stock item to add when you are passing them in to the function as a StockItem object?
Guess something is wrong here:
#Override
public void addItem(StockItem item) {
StockItem aItem = new StockItem(StockItem.getItemID(),
StockItem.getItemDesc(), StockItem.getPrice(), StockItem.getQuantity(), StockItem.getReOrderLevel());
StockItems.add(counter, aItem);
counter++;
}
All those getters are static methods. It does not make sense to me since I would think you want to get instance variables belonging to different objects. You must have initialiazed the StockItem class instance variables with the values printed out, otherwise I do not think your code would even compile.
Anyway why not adding the item passed as a parameter directly to the stock list?
Like so:
#Override
public void addItem(StockItem item) {
StockItems.add(counter, item);
counter++;
}
Basically I have multiple classes and I'm trying to get an array of LineItem for each Item that a customer purchases. LineItem includes the UPC, Description, Price, Quantity, SubTotal and Discount which is all stored in a seperate class. I'm trying to get it that when you use the method addItemToSaleList it will add to the array. I need to use an array and not an array list, so I have to copy over the array to a temp array, and then recreate a new array adding to the number the array can store and then recopying it over. I'm stuck getting the array to generate. Below is the code I have
public class Product {
private double price;
private String description;
private String ProductCode;
private DiscountStrategy discoutStrategy;
public Product(double price, String description, String ProductCode, DiscountStrategy discoutStrategy) {
this.price = price;
this.description = description;
this.ProductCode = ProductCode;
this.discoutStrategy = discoutStrategy;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getProductCode() {
return ProductCode;
}
public void setProductCode(String ProductCode) {
this.ProductCode = ProductCode;
}
public DiscountStrategy getDiscountStrategy() {
return discoutStrategy;
}
public void setDiscoutStrategy(DiscountStrategy discoutStrategy) {
this.discoutStrategy = discoutStrategy;
}
}
public class LineItem {
private Product product;
private double quantity;
public LineItem(Product product, double quantity) {
this.product = product;
this.quantity = quantity;
}
//Calculates the Discount Amount whether or not it's a percentage or dollar
//off
public double getDiscountAmount () {
return product.getDiscountStrategy().getDiscount(product.getPrice(), quantity);
}
//Calculates the Subtotal, gets the quantity from the DiscountStrategy and then
//the price from the product
public double getSubTotal() {
return quantity * product.getPrice();
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public double getQuantity() {
return quantity;
}
public void setQuantity(double quantity) {
this.quantity = quantity;
}
public class Receipt {
private LineItem[] lineItem = new LineItem[0];
public Receipt(LineItem[] lineItem) {
this.lineItem = lineItem;
}
public void addProductToTotalSale(LineItem li) {
addItemToSaleList();
}
public void addItemToSaleList() {
LineItem[] tempItemList = new LineItem[lineItem.length + 1];
for (int i = 0; i < tempItemList.length; i++) {
tempItemList[i] = lineItem[i];
}
lineItem = new LineItem[tempItemList.length];
for (int j = 0; j < lineItem.length; j++) {
lineItem[j] = tempItemList[j];
}
}
public LineItem[] getLineItem() {
return lineItem;
}
I would remove addItemToSaleList() and implement addProductToTotalSale(LineItem) like so
public void addProductToTotalSale(LineItem li) {
// Allocate the memory.
LineItem[] tempLineItem = new LineItem[1 + lineItem.length];
// Copy the array.
if (lineItem.length > 0) {
System.arraycopy(lineItem, 0, tempLineItem, 0, lineItem.length);
}
// add the new item to the new slot.
tempLineItem[lineItem.length] = li;
// update the internal array reference.
lineItem = tempLineItem;
}
Next, you should protect your constructor from null;
public Receipt(LineItem[] lineItem) {
// Try and protect from bad calls, removes need to check for nulls in
// add (addProductToTotalSale) routine.
if (lineItem != null) {
this.lineItem = lineItem;
}
}
Because you provide a default 0 sized array your code appears to be safe to continue to include the default constructor. But, you might consider making your Receipt class immutable.
I'm not sure why you are making two new arrays. You only need one...
public void addProductToTotalSale(LineItem li) {
addItemToSaleList();
lineItem[lineItem.length-1] = li;
}
public void addItemToSaleList() {
LineItem[] tempItemList = new LineItem[lineItem.length + 1];
for (int i = 0; i < tempItemList.length; i++) {
tempItemList[i] = lineItem[i];
}
lineItem = tempItemList;
}
I am writing an addition to a java inventory problem that uses an arraylist to write methods to add, search for, etc. items in an inventory.
I am using another class called InventoryItem which has variables for sku, itemName, price, and stock.
I would like to know if I am on the right track in using a perviously defined class in writing a method to add an item.
import java.util.*;
public class Warehouse {
private ArrayList<InventoryItem> inventory = new ArrayList<InventoryItem>();
public static void addItem(InventoryItem i )
inventory.add(i);
}
public static void main(String [] args) {
addItem();
}
}
This is the InventoryItem class;
public class InventoryItem {
private int sku;
private String itemName;
private double price;
private int stock;
public InventoryItem (int sku, String itemName, double price, int stock) {
this.sku = sku;
this.itemName = itemName;
this.price = price;
this.stock = stock;
}
public int getSku() {
return sku;
}
public String getitemName () {
return itemName;
}
public void setPrice (double price) {
this.price = price;
}
public double getPrice () {
return price;
}
public void setStock(int stock) {
this.stock = stock;
}
public int getStock() {
return stock;
}
#Override
public String toString() {
return String.format("[%d ,%s ,%1.2f ,%d]", sku, itemName, price, stock);
}
public static void main(String[] args) {
InventoryItem itemName = new InventoryItem(1, "asdf", 2.4, 5);
System.out.println(itemName);
}
}
The major problem with your addItem() method is that it is static, so it won't be able to access the warehouse list, which is an instance variable that can only be accessed from an instance.
To fix this (and other) problems, try this:
public class Warehouse {
private List<InventoryItem> inventory = new ArrayList<InventoryItem>();
public void addItem(InventoryItem i)
inventory.add(i);
}
public static void main(String [] args) {
// create a Warehouse instance
Warehouse warehouse = new Warehouse();
// create an InventoryItem instance
InventoryItem i = new InventoryItem(sku, itemName, price, stock);
// add the InventoryItem to the Warehouse
warehouse.addItem(i);
}
}
You are on the right lines. When you call the addItem() method, you will need to pass in an InventoryItem object. So perhaps something more like:
double sku = 111;
String itemName = "someItem";
double price = 2.99;
int stock = 1;
InventoryItem inventoryItem = new InventoryItem(sku, itemName, price, stock);
addItem(inventoryItem);
You will of course need to make sure you have a constructor in your InventoryItem class which takes in the params that you need.
So, based on your InventoryItem class, and the extra tips from Bohemian below it would look like this:
import java.util.ArrayList;
import java.util.List;
public class Warehouse {
private List<InventoryItem> inventory = new ArrayList<InventoryItem>();
public void addItem(InventoryItem i) {
inventory.add(i);
}
public static void main(String [] args) {
// create a Warehouse instance
Warehouse warehouse = new Warehouse();
// create an InventoryItem instance
int sku = 111;
String itemName = "someItem";
double price = 2.99;
int stock = 1;
InventoryItem i = new InventoryItem(sku, itemName, price, stock);
// add the InventoryItem to the Warehouse
warehouse.addItem(i);
}
}