Getting content of LINKMAP properties in a Java HashMap - java

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.

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 values from hashmap in Eclipse

I am adding to a project done in Eclipse that displays data pulled from various databases to a webpage. I am trying to figure out how to use a hashmap. I have a variable/column called "description" that will show a description based on the value of the column just before it. The descriptions are in my hashmap. I just don't know how to pull the "description" value.
Here is part of the DtoBuilder -
private HashMap<String,String> itemDescrMap = null;
public VersionsDto build(Versions oneVersion){
VersionsDto result = null;
if(itemDescrMap==null){
itemDescrMap = loadItemDescrMap();
}
// Create instance of versions object and build it.
if(oneVersion != null){
result = new VersionsDto();
result.setStore(oneVersion.getStore());
result.setUpdatePackage(oneVersion.getUpdatePackage());
result.setDescription(oneVersion.getDescription());
and here is part of the hashmap -
private static HashMap<String,String> loadItemDescrMap(){
HashMap<String,String> map = new HashMap<String,String>();
map.put("CDSA", "Color Match");
map.put("CDSB", "New Formula Book");
map.put("CDSC", "Base Assignments");
map.put("CDSD", "Product Formulation");
map.put("CDSE", "Old TAC");
map.put("CDSF", "Colorant Systems");
map.put("CDSG", "Miscellaneous");
map.put("CDSH", "AFCD");
Initially, I was just grabbing the same data for "description" as I was for "updatePackage", just to test that it would populate all the fields and display it to the webpage. So now I need to know how to set the "description" value based on the hash map, where the first values (CDSD, CDSE, etc) are all the possible values in the "updatePackage" column and the second value is the corresponding "description" that I need.
Look at the javadoc https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
I think itemDescrMap.get(oneVersion.getUpdatePackage()) should do the job

Convert a map.values() returned Collection to List

I have tried everything I knew and whatever I found online but it just is not working. I keep getting:
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.mycompany.myproject.dto.MyDto
I would appreciate if somebody could please tell me what I am doing wrong in the code below:
List<Map<Long, MyDto>> dtoList = restTemplate.getForObject(myRestUrl + "/some-path/dtoInfo/" + ids, List.class);
Map<Long, MyDto> myMap = dtoList.get(0);
System.out.println("myMap SIZE is: " + myMap.size());
System.out.println("myMap is: " + myMap);
List<MyDto> dtos = new ArrayList<MyDto>(myMap.values());
StringJoiner sj = new StringJoiner(",");
for(MyDto obj : dtos) {
sjStoreIds.add(obj.getId());
}
The REST call comes back with a List containing a HashMap object with the "Key" of type Long and the "Value" of type MyDto.
Then I am printing the "Size" of the map and the map itself. Both prints the correct and expected information.
Then I am extracting the list of values from the map as below:
List<MyDto> dtos = new ArrayList<MyDto>(myMap.values());
No issues there.
However, when I am trying to go through the object in the converted list (dtos) as below:
for(MyDto obj : dtos) {
sjStoreIds.add(obj.getId());
}
I get java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.mycompany.myproject.dto.MyDto for for(MyDto obj : dtos) { part.
Spinning my brains for more than 2 hours now. :(
I am sure it's going to something very basic and I will be pissed and embarrassed once I know it but can anybody please tell me where I am doing wrong?
EDIT
Following is the REST implementation I have server-side:
#Override
public List<Map<Long, MyDto>> getInfo(String idValues) {
List<Map<Long, MyDto>> returnList = new ArrayList<>();
Map<Long, MyDto> result = new HashMap<>();
String[] ids = idValues.split(",");
for(String id : ids) {
result.put(Long.parseLong(id), testInfo.get(Long.parseLong(id)));
}
returnList.add(result);
return returnList;
}
The "testInfo" above is a map that gets built as result of SQL query.
restTemplate.getForObject is returning you something that isn't actually a List<Map<Long, MyDto>>. All the code you've shown is typesafe and correct, but getForObject silently skips type checking in its signature, and that's biting you. Figure out what type it really is. (From what you've shown us, it's probably a List<Map<Long, Map<Something, Something>>>.)

Unsure how this piece of code is doing what it does… .getDescribe()

I'm relatively new to Apex and Java.
Could someone possibly explain this snippet of code?
Map<String, SObjectField> m = Opportunity.SObjectType.getDescribe().fields.getMap();
for (String name : m.keySet()) {
DescribeFieldResult r = m.get(name).getDescribe();
System.debug(r);
}
I know it's getting the Describe information for each field on the Opportunity object, but could someone explain, line by line, how it's doing it?
Cheers!
This is about as basic as it gets when you need to enumerate a map:
Line 1 gets the map, and stores it in variable m
Line 2 iterates over the keys of the map m, using name variable for the value of the key in this iteration
Line 3 gets the item from the map m using name for the key, and calls getDescribe
Line 4 passes the result to System.debug
Line 5 closes the loop
However, this is not the best way of iterating the values, though: a simpler approach would be as follows:
Map<String, SObjectField> m = Opportunity.SObjectType.getDescribe().fields.getMap();
for (SObjectField val : m.values()) {
System.debug(val.getDescribe());
}
For completeness, if you would like to iterate both keys and values, iterate entrySet, like this:
Map<String, SObjectField> m = Opportunity.SObjectType.getDescribe().fields.getMap();
for (Map.Entry<String,SObjectField> e : m.entrySet()) {
// e.getKey() produces the key
// e.getValue() produces its associated value
}
Iterating keys and then retrieving the values in a separate call to get is inefficient.

Can you reference a java variable from a string?

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.

Categories