How to get inner key in map - java

I want to get inner value of map. Here is the map.
{
"CUADO3": [
{
"C_E": 101,
"DESCRIPCION": "zz",
"N_M": 385.19,
"N_A": 37.45,
"MS_M": 62.2,
"MES": 16.42,
"ME": 79.91,
"MEF": 3.16
}
]
}
Here is my java code
Map<String,Object> map = dao.getVlaues();
IF I want to get with key I can Call Like
Object cua = map.get("CUADO3");
But I need inside of CUADO3 C_E I need How Can I get C_E from map.

If you are sure about the structure then you can cast the object to desired List and Map classes like below and fetch the internal map, then get any desired value from internal map.
Map<String,Object> map = dao.getVlaues();
List<Map> listOfMap = (List<Map>)map.get("CUADO3");
Map internalMap = listOfMap.get(0);
System.out.println(internalMap.get("C_E"));

Related

java.util.concurrentModification Exception while Iteration over JSONObject

I've this following code chunk using which i want to store the value in JSONObject in order to iterate over it and render it over front end.
JSONObject dlCovs = jsonObject.getJSONObject("result").getJSONObject("cov_details");
Iterator x = dlCovs.keys();
while (x.hasNext()){
String key1 = (String) x.next();
String value1 = dlCovs.optString(key1);
dlCovs.put("covabbrv",key1);
dlCovs.put("dcIssuedt",value1);
dlCovs.put("vecatg",key1);
dlData.put("dlCovs", dlCovs);
}
/* dlCovs.put("covabbrv",cov);
dlCovs.put("issue_date",issue_date);*/
dlObj.put("status","valid");
dlData.put("dlCovs", dlCovs);
dlData.put("status","valid");
while iterating over the data in while loop i'm getting java.util.concurrentModificationException, their is also a case when i'm trying to debug it it is storing the value in dlData.put("dlCovs",dlCovs), but as soon as it's coming for iteration for the second time it throws error.
I've following JSON value
"cov_details": {
"MCWG": "NA",
"3WTR": "NA",
"PSV BUS": "NA",
"LMV": "NA",
"INVCRG": "NA"
},
Any help will be highly appreciable,thanks well in advance
enter code here
You're modifying the map whilst iterating its entries. You can't do that.
Put the items into a separate map, then add that to your "main" map afterwards:
Map newEntries = new HashMap();
Iterator x = dlCovs.keys();
while (x.hasNext()){
String key1 = (String) x.next();
String value1 = dlCovs.optString(key1);
newEntries.put("covabbrv",key1);
// .. etc
}
dlCovs.putAll(newEntries);
Also: don't use raw types. You should be declaring x like:
Iterator<String> x = dlCovs.keys();
then you don't need the cast:
String key1 = x.next();
Similarly:
Map<String, String> newEntries = new HashMap<>();
While iterating over maps using an iterator you cannot change the underlying map. It is called a Fail fast iterator which reads directly from the underlying structure. Java maintains an internal flag called mods which counts the number of structural changes made to the map. If the iterator finds mods to change while it is iterating, then it throws a Concurrent Modification Exception.
In Java concurrent hash maps do solve the problem by implementing fail safe iterators. Main thing is you cannot change the structure of map while iterating

Getting content of LINKMAP properties in a Java HashMap

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.

how to insert values in sorted order in Guava Table values

I've been trying to insert some values in sorted order in Table structure for Guava, below is my piece of code
NodeDetails node1 = new NodeDetails();
NodeDetails node2 = new NodeDetails();
NodeDetails node3 = new NodeDetails();
node1.setCLOUDTYPE("aws");
node1.setNODENAME("node1");
node2.setCLOUDTYPE("cloudstack");
node2.setNODENAME("node2");
node3.setCLOUDTYPE("azure");
node3.setNODENAME("node3");
Table<String, String, Object> table = TreeBasedTable.create();
table.put("vmstat_usage", "cpu_idle", node1);
table.put("vmstat_usage", "cpu_idle", node2);
table.put("vmstat_usage", "cpu_idle", node3);
table.put("vmstat_usage_percent", "cpu_system", node3);
Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting()
.create();
System.out.println(gson.toJson(table.rowMap()));
Here NodeDetails is implementing Comparable with which I want to sort the values... But when I'm taking the values of rowMap the same is overriding with existing values. So only one object is returning.
If I create TreeMultimap I'm getting all the objects inserted in collection correctly.
I'm trying to create this kind of response through this.
{
"vmstat_usage": {
"cpu_idle": {
"CLOUD_TYPE": "azure",
"NODE_NAME": "node3",
},
{
"CLOUD_TYPE": "aws",
"NODE_NAME": "node1",
},
{
"CLOUD_TYPE": "cloudstack",
"NODE_NAME": "node2",
"NODE_PRIVATE_IP_ADDRESS": null
}
},
"vmstat_usage_percent": {
"cpu_idle": {
"CLOUD_TYPE": "azure",
"NODE_NAME": "node3",
}
}
}
I've gone through this link Sorting Guava table on values and found that "table.rowMap returns a SortedMap>. So the map is sorted on it's row keys, but the Map value is an unsorted map"
As suggested here Java Sort a Guava TreeBasedTable I can create a new TreeTable with defined comparator and put my previous Table in there or http://www.wenda.io/questions/2486554/sorting-guava-tables-in-descending-order-based-on-values.html I can create new Ordering while create the Table.
I tried something like this but it's not working.
Table<String, String, NodeDetails> table2 = TreeBasedTable.create(Ordering.natural(), Ordering.natural());
table2.putAll(table);
Please give me an example for how to do this.

java list<map> with repeated values

I have a List<Map> which should be of the below syntax:
[{clientName=abcd}, {clientName=defg}]
Previously I had List<Bean> which I want to replace with List<Map>.
Here is my code:
List<Map> clientList=new ArrayList<Map>();
Map<String,String> clientNameMap = new HashMap<String,String>();
clientNameMap.put("clientName","abcd");
clientList.add(clientNameMap);
clientNameMap.put("clientName","defg");
clientList.add(clientNameMap);
What happens with this code is, I am getting [{clientName=defg}, {clientName=defg}] as the output where, clientName=abcd is replaced by the 2nd value defg. How can I get the expected result which is [{clientName=abcd}, {clientName=defg}]?
Thanks
You have to re-initialize your Map<> again before adding to List<> because you are changing previous reference for Map<> object and on same key that will change previous object also.
You code should be :
List<Map> clientList=new ArrayList<Map>();
Map<String,String> clientNameMap = new HashMap<String,String>();
clientNameMap.put("clientName","abcd");
clientList.add(clientNameMap);
clientNameMap = new HashMap<String,String>(); //Initialize it again.
clientNameMap.put("clientName","defg");
clientList.add(clientNameMap);
First read up on Map and List. When you add a Map object (or any other object) to a List object, all you're doing is adding a reference to that object in the List.
It means that if you change the Map contents after adding it to the List object, that will be reflected in the List.
In a Map, moreover, the key has to be unique.
So here you need to create a new Map object before you can add the new value and add that new Map object to the list.
See this other post for details:copying a java hashmap
Try below code, Map key should be unique so when you put value to same key n times the value is just replaced for the key, In your code you are replacing the value for same key(clientName) and adding it to list so it is printing the same value which you put in last to map.
List<Map> clientList=new ArrayList<Map>();
Map<String,String> clientNameMap = new HashMap<String,String>();
clientNameMap.put("clientName-1","abcd");
clientList.add(clientNameMap);
clientNameMap.put("clientName-2","defg");
clientList.add(clientNameMap);

Obtain Inner JSON Array Values

I'm attempting to get the values for the "filterInputParameters" array within the serviceResponseValue map. Right now I have attempted to iterate through the map but could only obtain the first level of data such as the displayName and I need to go one-two levels deeper for the values in filterInputParamters array. Please let me know if you need more information.
Dart Code:
var jsonString = response;
var dropDown = querySelector("#asset");
Map jsonObject = JSON.decode(jsonString) as Map;
dropDownList = jsonObject["serviceResponseValue"] as List<Map>;
LinkedHashMap<String, Map> dataMap = new LinkedHashMap<String, Map>();
//the one causing issues and returning null
var ddValues2 = dropDownList
//extract the 'displayValue'
.map((e2) => e2['filterInputParameters']['value']);
//create a set to eliminate duplicates
//.toSet().toList()
//sort the result
//..sort();
ddValues2.forEach((e2) {
print(e2);
});
Map jsonObject = JSON.decode(jsonString) as Map;
print(jsonObject["serviceResponseValue"][0]["filterInputParameters"]);
In JSON [ ] indicate a List and { } a Map.
You access a list element by passing a numeric index (xxx[5] to get the 6th item)
and a String to access a Map item (xxx["serviceResponeValue"]).
Your JSON starts with
{ // the outer element is a map
"serviceResponseValue":[ // this map item can be accessed with a
// string index"serviceResponseValue"
// after the colon `:` starts the associated value, a list
// the first item can be accessed using [0]
{ // which contains a map
...
"filterInputParameters":[ // this item of the map is returned by ["filterInputParameters"]
{
"id":"8a4984e047d0e40d0147d0e410020008",

Categories