Java - get variable name from double array - java

I have a Java array of type double with variable names used to store values as so:
double [] countArray = {teaCount, hotMealCount, drinkWaterCount, phoneCallCount};
I am looking to print the names of the variables out by it's index.
e.g. If I request countArray[0] it would return teaCount instead of the double that's stored.

If you want the names you need to store these
String[] countArray = {"teaCount", "hotMealCount", "drinkWaterCount", "phoneCallCount"};
Though most likely you wanted a Map<String, Double> such as
Map<String, Double> map = new LinkedHashMap<>();
map.put("teaCount", teaCount);
map.put("hotMealCount", hotMealCount);
map.put("drinkWaterCount", drinkWaterCount);
map.put("phoneCallCount", phoneCallCount);
This stores both the name and the value it has.

You can't do it the way you want but the Map coould be your solution:
Map<String, Double> count = new HashMap<String, Double>();
count.put("teaCount", 1.5);
count.put("hotMealCount", 2.5);
// etc
count.get("teaCount"); // 1.5

What you want to do is not possible with this approach. A solution would be to have a Map<String, Double> where you store the name as key and the count as the value in the Map.
Actually the variable name is something temporarily and you cannot access the name later. And if you add something to an array you do not add the variable by name to the array but the value location.

Yor are storing Strings, not double values in the array.
If you want to print the value of an index, just use:
System.out.println(countArray[0]);
And that will print teaCount.
Hope it works.

Related

Make a registry/database list in Java

I wonder how to make a registry/database list in Java. I mean if I, for example, have a variable called "data", and then I add a new entry to that called "name" with the value "David". Then I would call something like "data.name" to get the value "David".
As seen on this picture
I've been Googling but not finding anything about it.
It sounds like you want a Map from String to String. You can use a HashMap<String,String> for that.
// Create Map using HashMap
Map<String, String> data = new HashMap<String, String>();
// Set name
data.put("name", "David");
// Get name
String name = data.get("name");
System.out.println(name);

Get total for unique items from Map in java

I currently have a map which stores the following information:
Map<String,String> animals= new HashMap<String,String>();
animals.put("cat","50");
animals.put("bat","38");
animals.put("dog","19");
animals.put("cat","31");
animals.put("cat","34");
animals.put("bat","1");
animals.put("dog","34");
animals.put("cat","55");
I want to create a new map with total for unique items in the above map. So in the above sample, count for cat would be 170, count for bat would be 39 and so on.
I have tried using Set to find unique animal entries in the map, however, I am unable to get the total count for each unique entry
First, don't use String for arithmetic, use int or double (or BigInteger/BigDecimal, but that's probably overkill here). I'd suggest making your map a Map<String, Integer>.
Second, Map.put() will overwrite the previous value if the given key is already present in the map, so as #Guy points out your map actually only contains {cat:55, dog:34, bat:1}. You need to get the previous value somehow in order to preserve it.
The classic way (pre-Java-8) is like so:
public static void putOrUpdate(Map<String, Integer> map, String key, int value) {
Integer previous = map.get(key);
if (previous != null) {
map.put(key, previous + value);
} else {
map.put(key, value);
}
}
Java 8 adds a number of useful methods to Map to make this pattern easier, like Map.merge() which does the put-or-update for you:
map.merge(key, value, (p, v) -> p + v);
You may also find that a multiset is a better data structure to use as it handles incrementing/decrementing for you; Guava provides a nice implementation.
As Guy said. Now you have one bat, one dog and one cat. Another 'put's will override your past values. For definition. Map stores key-value pairs where each key in map is unique. If you have to do it by map you can sum it just in time. For example, if you want to add another value for cat and you want to update it you can do it in this way:
animals.put("cat", animals.get("cat") + yourNewValue);
Your value for cat will be updated. This is for example where our numbers are float/int/long, not string as you have. If you have to do it by strings you can use in this case:
animals.put("cat", Integer.toString(Integer.parseInt(animals.get("cat")) + yourNewValue));
However, it's ugly. I'd recommend create
Map<String, Integer> animals = new HashMap<String, Integer>();

Which Map class should I use for data consisting of different types?

It seems that HashMap is limited to only one value, and I need a table of values like:
Joe(string) 25(Integer) 2.0(Double)
Steve(string) 41(Integer) 1.6(Double)
etc.
I want to store infomation similarly as in two-dimensional array, but I want it to have different variable types. I've look at various Map-implementing classes, but it seems that they only store value (assigned to a key), or two variables (I need at least three). What class should I use for this?
It sounds like you should be creating a separate class with a String field, an int field and a double field.
Then you can create a map with that as the value type, and whatever type you like as a key. For example:
Map<String, Person> map = new HashMap<>();
// What keys do you really want here?
map.put("foo", new Person("Joe", 25, 2.0));
map.put("bar", new Person("Steve", 41, 1.6));
Or it's possible that you don't even need a map at all at that point:
List<Person> list = new ArrayList<>();
list.add(new Person("Joe", 25, 2.0));
list.add(new Person("Steve", 41, 1.6));
Make class representing data you want to store, eg.
class Person {
String name;
//rest
}
and then make map like Map. Type of map is irrelevant
I would suggest that you create a simple class that stores the integer and double pair, which is then mapped to a String (I assume this is the desired outcome).
HashMap<String, Pair<Integer, Double>> map = new HashMap<String, Pair<Integer, Double>>;
map.put("Steve", new Pair<Integer, Double>(41, 1.6));
Where Pair is defined as
class Pair<T, K> {
public T val1;
public K val2;
public Pair(T val1, K val2){
this.val1 = val1;
this.val2 = val2;
}
}
There are a number of ways to do this.
The best way is the way that is suggested by Jon Skeet and #novy1234. Create a custom class that represents a person (or whatever the rows of the table are). Then use either a Map or a List of that class to represent the "table". (The Map allows you to select one of the fields / columns as a key ... if that is appropriate.)
So you might end up with a HashMap<String, Person> or an ArrayList<Person> ... where Person is your custom class.
A second way would be to represent each row as a Map<String,Object> so that (for example) "name" maps to "Joe", "age" maps to 25 and "height" maps to 2.0. (He is tall.) Then the table could be either a Map or a List of those maps.
A variation of the second way would be a Map<String, Map<String, Object>> where the keys of the outer map are each person's name, the keys of the inner map are the field names; e.g. "age" and "height".
However using a Map<String, Object> to represent a row is not a good Java solution when the set of columns is known. A custom class will use significantly less space than a Map (of any flavour), and a regular getter method is orders of magnitude faster that a Map.get(key) method. In addition, the Map.get(...) method is going to return you an Object that has to be cast to the expected type before it can be used. There is a risk that the typecast will fail at runtime, because you have (somehow) populated the row / map incorrectly.
You should only contemplate using a Map to represent a row in the table if the columns are not known at compile time, or if there are an unmanageably number of columns that are populated sparsely. (Neither is the case here ...)
So, which Map class should you use?
Your alternatives include HashMap, TreeMap, LinkedHashMap and ConcurrentHashMap. Each one has different properties and different target use-cases. However, if your table is small, and in the absence of specific requirements, it probably makes no real difference.
Make a node to store both the integer and double values?

Getting the user to name the variables

For my program i want to have it so that the user can name the variables a bit like in a game you would name your charecter/world. I looked it up and couldn't find anywhere that said if this is possible and if so how it is done.
As many others have said, you can't dynamically name variables.
You can however make a Map
It would allow you to create any name for a variable such as "MyTestVar" at runtime and use it as a key in that map to whatever you put:
Map<String, String> myMap = new HashMap<String, String>();
String varName = getVariableNameFromUser();
String value = getValueFromUser();
myMap.put(varName, value);
// ... later
String whatVariableDoYouWantTheValueOf = getVarNameFromUser();
String storedValue = myMap.get(whatVariableDoYouWantTheValueOf);
System.out.println("The value for that is: " + storedValue);
What you can do is create a linked list or an arraylist of some type of object that you create. Your object can then have two properties (or more) where one is the name, and the other is the value. You can then search for an object in your list based on the name, and return the value that you want. This will basically accomplish what you're trying to achieve.
You can't get a user to name a variable. All you can do is allow the user to set the variable's value.
I guess what you mean is something like giving Tags or Labels to Objects. "Variable Names" is a missleading wording for that.
After the User typed in the name string for an obj Object, you could for example use a HashMap<String, Object> to store the user input:
Map<String, Object> tagToObjectStore = new HashMap<String, Object>();
String userInput = "any Tag name";
Object somethingToLabel = ... // TODO
tagToObjectStore.put(userInput, somethingToLabel); // store the user input
// later in code...
Object theStoredObject = tagToObjectStore.get(userInput); // get the stored object
Is that what you are looking for?

Is the given initialization of an associative array wrong?

Suppose I define the following statement, will an array of dictionaries (key-value pairs) be created, with all keys initialized to "stringvalue1" and values to stringvalue2?
String exampledatastruct[] = { "stringvalue1", stringvlaue2 };
Is the above statement a bad way of using?
The above Collection type is unsuitable for keyed access. Use a Map:
Map<String, String> map = new HashMap<>();
map.put("stringvalue1", stringvlaue2);
That would simply give you an array with two String elements in it. The first would be the string "stringvalue1", the second would be whatever String the variable stringvalue2 references. There'd be no relation between the two, other than the fact they're in the same array.
What you wrote is an array, not a dictionary. A usual representation of java dictionary is java.util.Map. For example:
Map<String, String> dictionary= new HashMap<String, String>();
you would put values in the dictionary in this way:
dictionary.put("key", "value");
and would get values from the dictionary in this way:
String value= dictionary.get("key");
You are creating a String array, not an associative array. You should use the java Map interface. Also, you can only have 1 key "stringvalue1".

Categories