Reputation: 997
I'm designing a system which needs a specific collection, it is written in Java. I need to store the history of prices of stock (dates and time).
One stock can have multiple dates and times as I want to show the previous prices.
Which collection would I use to map a stock id to multiple dates AND times?
I know there are HashTables, but I can't see how they will work as they still take only a key and a value. I have a stock class, within it I want a collection which takes and a value and a value.
Upvotes: 2
Views: 506
Reputation: 11960
You could create a hashtable containing another type of collection. For example, if your stock IDs are Integers and being able to see the history of prices chronologically is your main use case, create a hashtable of arraylists, and keep the arraylists sorted by date:
HashMap< Integer, ArrayList<Stock> > stockCollection = new HashMap< Integer, ArrayList<Stock> >();
Or, if you really need to be able to access the stock price for a particular date in O(1) time, create a hashtable of hashtables:
HashMap< Integer, HashMap<Date, Stock> > stockCollection = new HashMap< Integer, HashMap<Date, Integer> >();
Upvotes: 1
Reputation: 66637
One option would be using google guava multi-map (If you are ok to include third party jars).
multi-map allows you to add elements with same key.
Here is simple tutorial.
EDIT:
If not allowed to use guava, then another option would be:
HashMap<String, ArrayList<Stock>> map = HashMap<String, ArrayList<Stock>>()
Here Stock
is simple POJO class with timeStamp and stock symbol.
Upvotes: 4
Reputation: 823
You can use HashMap where key will be stockid and value will be arraylist of the objects which contain date and time.
Map<Integer, ArrayList<Price>> anyname = new HashMap<Integer, ArrayList<Price>>();
Upvotes: 1
Reputation: 28687
You could use a map of the stock IDs as the key, and a list of prices as the value.
Map<Integer, List<Price>> stocks = new HashMap<Integer, List<Price>>();
Upvotes: 2
Reputation: 25950
Suppose you have a Price
object, then you can use a map like this:
HashMap<String, ArrayList<Price>> map = HashMap<String, ArrayList<Price>>();
Of course you can change your key type to your own.
Upvotes: 2