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);
Related
I'm trying to work with LINKMAP properties.
Let's say we have Vertex PokemonMaster as follow
PokemonMaster
{
name, (STRING)
age, (INTEGER)
pokemons, (LINKMAP) of Pokemon
}
Containing a LINKMAP of Pokemon
Pokemon
{
name, (STRING)
}
The following code is working to create a PokemonMaster giving him some Pokemon :
Map<String, ODocument> pokemons = new HashMap<>();
ODocument pikachu = new ODocument("Pokemon");
pikachu.field("name", "Pikachu");
pikachu.save();
ODocument raichu = new ODocument("Pokemon");
raichu.field("name", "Raichu");
raichu.save();
pokemons.put("pikachu", pikachu);
pokemons.put("raichu", raichu);
graph.addVertex("class:PokemonMaster", "name", "Sacha", "age", "42", "pokemons", pokemons);
Now what we've got in the DB is something like :
{"pikachu":"#15:42","raichu":"#15:43"}
for Sacha, #15:42 and #15:43 being the rids of pikachu and raichu.
Here is my problem :
I can't get this Map into a Java HashMap.
What I mean is, i would like to be able to do something like :
Vertex v = graph.getVertex(id); // getting the instance of Sacha
Map<String, ODocument> map = v.getProperty("pokemons");
System.out.println(map.get("pikachu").getIdentity());
System.out.println(map.get("raichu").getIdentity());
This was my first try, then i thought this would not make sense to get an ODocument as value since it's an id which is store in the table.
So I tried :
Vertex v = graph.getVertex(id); // getting the instance of Sacha
Map<String, String> map = v.getProperty("pokemons");
Hoping to get the id in the value.
But nothing is working, saying the following error :
com.tinkerpop.blueprints.impls.orient.OrientElementIterable cannot be cast to java.util.Map
So I tried OrientElementIterable as follow :
Vertex v = graph.getVertex(id); // getting the instance of Sacha
OrientElementIterable<Element> test = v.getProperty("pokemons");
for (Element elem : test) {
System.out.println(elem.getProperty("name"));
}
And it actually worked, printing me "Raichu" and "Pikachu". But this is transforming my Map into a simple list, and I'm losing the key/value feature.
My question is, is there a way to get the LINKMAP properties into a Java Map?
I know this is working with EMBEDDEDMAP, but i'd like it to work with LINKMAP
EDIT : FIRST SOLUTION
I found a first solution for those who need
It's possible to change the Vertex into a ODocument like :
ODocument doc = new ODocument(new ORecordId(v.getId().toString()));
And then we can get the map easily :
Map<String, ORecordId> map = doc.field("pokemons");
And then the key contains the name of the pokemon and the value represents the id of his instance.
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?
I have a method that read from database and get some string there. According what I get I will override that string for another that I already know. For example:
str → string
bin → binary
and so on..
My question is, what is the best practice for doing this? Of course I already thought about if's...
if (str.equals("str"))
str = "string";
A file that have this things pre-defined, a multi-dimensional array, etc.. But this all seems a quite newbie, so what do you recommend? What is the best way?
Use a Map:
// create a map that maps abbreviated strings to their replacement text
Map<String, String> abbreviationMap = new HashMap<String, String>();
// populate the map with some values
abbreviationMap.put("str", "string");
abbreviationMap.put("bin", "binary");
abbreviationMap.put("txt", "text");
// get a string from the database and replace it with the value from the map
String fromDB = // get string from database
String fullText = abbreviationMap.get(fromDB);
You can read more about Maps here.
You could use a map, for example:
Map<String, String> map = new HashMap<String, String>();
map.put("str", "string");
map.put("bin", "binary");
// ...
String input = ...;
String output = map.get(input); // this could be null, if it doesn't exist in the map
Map is a good option as people have suggested. The other option which I normally consider in this scenario is Enum. It gives you an additional capability of adding behavior for a combination.
Hi I have a strange question about java. I will leave out the background info so as not to complicate it. If you have a variable named fname. And say you have a function returning a String that is "fname". Is there a way to say reference the identifier fname via the String "fname". The idea would be something like "fname".toIdentifier() = value but obviously toIdentifier isn't a real method.
I suppose a bit of background mite help. Basically I have a string "fname" mapped to another string "the value of fname". And I want a way to quickly say the variable fname = the value of the key "fname" from the map. I'm getting the key value pair from iterating over a map of cookies in the form . And I don't want to do "if key = "fname" set fname to "value of fname" because I have a ton of variables that need to be set that way. I'd rather do something like currentkey.toIdentifer = thevalue. Weird question maybe I'm overlooking a much easier way to approach this.
Why don't you just use a simple hashmap for this?
Map<String, String> mapping = new HashMap<String, String>();
mapping.put("fname", "someValue");
...
String value = mapping.get(key); //key could be "fname"
In a way you're describing what reflection is used for:
You refer to an object's fields and methods by name.
Java Reflection
However, most of the time when people ask a question like this, they're better off solving their problem by re-working their design and taking advantage of data structures like Maps.
Here's some code that shows how to create a Map from two arrays:
String[] keyArray = { "one", "two", "three" };
String[] valArray = { "foo", "bar", "bazzz" };
// create a new HashMap that maps Strings to Strings
Map<String, String> exampleMap = new HashMap<String, String>();
// create a map from the two arrays above
for (int i = 0; i < keyArray.length; i++) {
String theKey = keyArray[i];
String theVal = valArray[i];
exampleMap.put(theKey, theVal);
}
// print the contents of our new map
for (String loopKey : exampleMap.keySet()) {
String loopVal = exampleMap.get(loopKey);
System.out.println(loopKey + ": " + loopVal);
}
Here's a link to the JavaDoc for Map.
I am using a class where I am taking input as the file name and the file location. I have a pre defined file names, so I will match the predefined file names with the file name that I received and then store the values accordingly. Please look at the code below
//Set of storage maps and tables
public class storage
{
//Storage set
public static Set<Integer> tiger = new HashSet<Integer>();
//Storage set
public static Set<Integer> lion = new HashSet<Integer>();
//This is the table used for storing the browser customer count
public static Table<String,String,Integer> elephant = HashBasedTable.create();
//Storage map
public static Map<String, String> monkey = new HashMap<String, String>();
public static void storeDataDirector(String fileLocation,String fileName) throws Exception
{
if (fileName = monkey)
**update the "monkey map"**
}
This is my problem, also I have lot of maps and tables to be used so I wouldn't be able to use multiple if conditions and then check and update the same.
What I would like to know is the below
As I have said earlier, The file name that I am sending to the program which is "String filename" has the same name of the "Map monkey" but the former is a String and the latter is the map. I would like to know if I will be able to use the string variable as a reference to the map instance as both of them have the same name . This will highly avoid the if conditions that I am using in the program and thus I would like to possible solution for this ... Anything related to type caseting ort
You need to have another Map - whose key is a String and value is a Map. Something like Map<String,Map> allMaps = new HashMap<String,Map>()
Once you have this map , populate it with all your filenames and the corresponding maps monkey.
allMaps .put("monkey", monkey)
If a string filename corresponds to not a map but to a set , then you need to declare something more general Map<String,Object> allMaps = new HashMap<String,Object>(). Ofcourse this means you need to cast the value to its particular type before you can do any meaningful thing with it.
Then , to use this map , use your filename argument
Map monkeyAgain = allMaps.get(filename)
You can use reflection:
Storage.class.getField(fileName).get(null)
You will still have to cast the returned object. I do not think this the right approach.
The idea is to relate them in a Map, and use the file name as a key for example
Map<String, Map<String, String>>
// file store structure
If you need a generic solution, you could solve this by implementing an abstraction of your store structure, by implementing an interface similar to this one:
// T is the store type and U is the original type (String from file for instance...)
public interface StoreUnit<T, U> {
void update(U record);
List<T> list();
}
so you will have an implementation for each case (Set, Map, Table ...) and will relate it in a map using the file name as key.
monkeyFileName => MapStoreUnit<Entry<String,String>,String>
tigerFileName => SetStoreUnit<Integer, String>
elephantFileName => TableStoreUnit<Entry<Entry<String,String>,String>,String> // not sure if for Table there is something better than Entry ;)
When you wanna update some store you perform a get over the map using the file name as key, and invoking update method implemented with the record (that could be an String, complex Object) and so on. When you need to read something from there you could use the list method.