To HashMap or not to HashMap? - java

I am trying to create some code that will read information off of a text file. For example Bus_Routes.txtwill contain Route_A.txt 283,284 and from that the file Route_A.txt is opened and it contains 2 columns, Latitude Longitude with the coordinates listed. This I wrote out fine.
From this I am trying to get the device with id 283 to travel along the coordinates in sequence. I was recommended to use a HashMap. So my plan is to create a HashMap for the coordinates of Route_A.txt, have one column for Latitude and the other for Longitude. From that I was going to create another HashMap that will contain the device_id and the HashMap containing the coordinates, and the device_id will travel through each step of the HashMap.
Can this be done or am I completely looking in the wrong area?
If anyone has any suggestions out there, they would be much appreciated

Don't store your coordinates in a HashMap. It would be difficult to store multiple coordinates with the key (latitude?) being the same. e.g. a simple Map<Integer, Integer> would only hold one longitude value for a latitude, and that would prevent your route from having multiple destinations along the same longitude line.
I would rather use:
List<Coord>
where Coord is your lat/long pair. The List will preserve order, whereas a normal HashMap wouldn't.
Note that I'm deliberately encapsulating the lat/long pair as a specific object. You could store it as a tuple of integers but I'd rather a specific object to enforce typing, permitting addition of functionality etc. As noted elsewhere, Java is an OO language and you shouldn't shy from creating classes to represent these concepts (a sign that you should do this is when you create something like Map<String,List<Integer,Integer>>)

A HashMap is a data structure that let's you associate a value with a key, and allows, given a key, to get back the value in constant time (without the need to loop as you would have to with a list or an array, for example).
So use this structure if your usecase needs such a functionality. Having devices stored in a map, where the device ID is the key, sounds like a good idea.
If, on the other hand, you want a data structure to contain fields (like latitude, longitude), then create a class. Java is an OO language. You should create your own classes. And if you want a list of coordinates, then you should use a List<Coordinate>, and not a HashMap.

Related

Storing multiple values for keys?

In Python, a dictionary can contain a key and many values for that key. I've been trying to look at Java, but there is no simple way of doing this without trying to use something like HashMap<String, List> I read that this way is very bad and it's called chaining and that it will cause a performance issue. I need to store more than hundreds of millions of keys so I need something that can scale. Each day this hash map will be emptied.
My HashMap needs to have 4 values per key like so: country, volume, network, and date. A fake example of a key looks like this: "EJTER" would it be efficient and feasible if I did something like this "EJTER_country", "EJTER_volume", "EJTER_network", "EJTER_date". These will be the keys and each respective key will have its own value. The only downside to this I see is that there will be 4x more keys than normal.
You can take a look at Guava MultiMap, it seems to be what you are looking for.

Point System Storage

I'm having trouble picking between an array, arraylist, or a list for one of the features of this small game I'm designing in Java. I'm not limited to those three, those are just the ones I know of.
The feature is that the player unlocks a certain text/button whenever they reach that certain amount of points. So, what I would like to store a "list" that contains a collection of two points. One point that gives the required point amount, and the second point is either a string or something else that would be unlocked.
I was leaning towards just a plain old 2-d array for this but decided to post it here so I could get more opinions.
If the two values are linked I would use a HashMap to store the values. This allows you to easily access the corresponding value. Example: (Assuming the points that are linked to the achievement are int's and the achievement is a String)
HashMap<Integer, String> hashmap = new HashMap<>();
assignments.put(18, "New Achievement");
//Etc
Where 18 is the number of points and New Achievement is the achievement the user has unlocked.
As chrylis said if the values are in continuous order a NavigableMapwould be a good choice to look into.
A good tutorial for the NavigableMap

User Defined Index for an ArrayList of IDs

I'm in a situation where (in Java) I need to define an arraylist of generated ids. I don't know how many would be generated at any given time, but I do know that when one is generated, the user who generated it would need to set a custom index, and be able to retrieve it by that index. What would be the generally accepted standard way of storing and working with a data structure like this? An arraylist of arrays?
Sounds like a use case for a Map which you can use the ID as the key and a value (or potentially an array of values, if multiple values can have the same id) as the value. You can then index into the map and retrieve data using the key. The benefit is that this works even if you want to change the ID from an int to a String or even some other idea.
The problem with using a List like this is if I have two ids 1 and 3000 then there are 2998 indices that are wasted, which is not exactly ideal.

Java Substitute Values In A Table

To save time on calculations, I am making a program that will use formula to calculate a value based on the data that the user inputs. The program will prompt the user for five double values: A, B, and C, D, and E. It will then multiply A by B and then find the corresponding value on a conversion table. It will do the same for C and D and plug in the corresponding values along with E in a formula to give the user the answer. My question is: How would I include the table of values I mentioned above into my program so that I can easily find the corresponding values? I'm thinking of hardcoding these values into hashmaps but that would take quite awhile. Is there a file format that stores similar types of data that would be optimal to the situation?
Store the values in CSV. Load the values into an custom object/class with a field for each column. Start by looping over the entire set of objects to find the correct value/range each time. If that does not perform well optimize by doing things like having multiple lists of references to the objects where each list is sorted by a different column-- use those sorted lists to quickly find the correct object.
I say "range" here, because I am assuming you are sometimes looking for doubles. If the result of your calculation tells you to look for 1.999999 you may actually have to look for that +/- some tolerance. For this same reason you wouldn't want to use doubles as the keys for a map.

2-dimensional object that can grow in java

I need to associate a unique key with each of a number of rectangle objects in Java. The key is in double data type, and the rectangles are obviously rectangle data types.
Currently, I have the rectangles in a vector, but they are not of much use to me unless I can also access their keys, as specified in the first paragraph above.
I would make a 2d array, with the first column being the key and the second column being the rectangle, but the number of rows in the array will need to change all the time, so I do not think an array would work. I have looked into vectors and arrayLists, but I am concerned about being able to search and slice the data.
Can anyone show me some simple java code for creating and then accessing a 2D data set with a variable number of rows?
Currently, my prototype looks like:
ArrayList<Double> PeakList = new ArrayList<Double>();
Vector<Rectangle> peakVector = new Vector<Rectangle>();
Vector<Double> keyVector = new Vector<Double>();
if(PeakList.contains((double)i+newStartingPoint)){
Rectangle myRect = new Rectangle(x2-5, y2-5, 10, 10);
boolean rectFound = peakVector.contains(myRect);
System.out.println("rectFound is: "+rectFound);
Double myPeak = ((double)i+newStartingPoint);
if(rectFound!=true){
peakVector.add(myRect);
keyVector.add(myPeak);
System.out.println("rectFound was added.");
}else{System.out.println("rectFound was NOT added.");}
}
I then enumerate through the data for subsequent processing with something like the following:
Enumeration e = peakVector.elements();
while (e.hasMoreElements()) {
g2.fillRect(peakVector.lastElement().x, peakVector.lastElement().y, 10, 10);
}
As you can see, there is no way to subsequently integrate the keys with the rectangles. That is why I am looking for a 2D object to use. Can anyone show me how to fix this code so that I can associate keys with rectangles and subsequently access the appropriately associated data?
Why not simply use a HashMap<Double, Rectangle>?
Edit: no, there are significant problems with this since there's no guarantee that two doubles will equal each other even though numerically they should. Does it have to be Double? Could use use some other numeric or String representation such as a Long? Is there a physical reality that you're trying to model?
Why not use a Map? They are specifically designed to associate keys with values. You can iterate through the keys of the map with keySet(), the values with valueSet() and both the keys and values at the same time with entrySet()
A Map will surely be the right answer, you don't worry about cardinality of the domain or of the codomain of the mapping function. Having double as the key datatype forbids you from using some of the predefined types.
I would go with a TreeMap<Double, Rectangle> just because the natural ordering is used to sort the entries inside the structure, so having a double is perfectly allowed, but you would have problems with the retrieval (I actually used myself floats as keys for maps and never had a problem with some precautions but it mostly depends on the nature of your data.

Categories