Getting values in hash map in Java - java

I am not a java developer, and this is not my homework or something. I am just in need of getting the values of these parameters: end & begin. this is what I have:
rs = [{}, {end=2013/11/5, begin=2012/11/6}]
I am wonder if I could get values like this:
rs[1].end
rs[1].begin
the source is:
protected QueryParameters prepareForm(final ActionContext context) {
final SearchErrorLogForm form = context.getForm();
Map<String, Object> rs = form.getValues();
System.out.println(rs);
/*the output is: {pageParameters={}, period={end=2013/11/5, begin=2013/11/6}} */
}
sorry, the rs type is hashmap.

That is not a valid statement.
A proper way of assigning an array would be:
String dates[] = {"2013/11/5","2012/11/6"};
String start = dates[0];
String end = dates[1];
There is a excellent tutourial at oracle docs
Okay, that is a Map containing two Maps as it seems. The first map named "pageParameters" is empty. The second one is named period and contains two items. The key "end" maps to the value "2013/11/5". The key "begin" maps to the value "2013/11/6".
To access the objects in the map you could do like this:
final Map<String, String> period = (Map<String, String>) rs.get("period");
final String begin = period.get("begin");
final String end = period.get("end");
If you would like to change a value in the map period you will need to overwrite the already existing one:
period.put("end", "NEW_END");
rs.put("period", period);
For further information, Oracle has great tutorials on Hashmaps.

you can do like following:
rs[1][0] for the first
rs[1][rs[1].length-1] for the last

Related

use reflection to set or get array in a Java Map

Is there a way to get or set an array element stored in a Java Map?
Example:
If we have a map like this:
{
name: "Blah",
friends: ["Foo", "Bar"]
}
Map<String, Object> myMap = new HashMap<>();
List<String> friends = new ArrayList<>();
myMap.put("name", "Blah");
myMap.put("friends", friends);
Is it possible to use Reflection to get or set the first element in the friends array in the "myMap" from the string: "myMap.friends[0]"
Your question is not very clearly written and I believe that's why you are not getting the answer you expect but, If I understood your question correctly, you need to parse the following input string at runtime that you don't know beforehand:
myMap.friends[0]
And this should be parsed into components like:
mapName = "myMap"
mapKey = "friends"
valueIndex = 0
And with this information, you need to manipulate data in a Map at runtime through reflection.
Note: This only makes sense if you could potentially have more complex expressions, using different sort of objects and accessing nested properties of retrieved objects, otherwise you wouldn't need reflection at all.
Note 2: You may want to have a look at JXPath which already does a lot of this for you based on a XPath-like syntax for navigating object graphs.
That said, if my assumptions are correct and you still want to do it yourself, consider the following example.
For the sake of demonstration, let's consider our map is returned by a method myMap inside a Context.
private static class Context {
public Map<String, Object> myMap() {
Map<String, Object> myMap = new HashMap<>();
List<String> friends = new ArrayList<>();
friends.add("Foo");
friends.add("Bar");
myMap.put("name", "Blah");
myMap.put("friends", friends);
return myMap;
}
}
I'm assuming you are already parsing the input string into the different components. If not, for this simple string you could do it with simple regular expressions. If you already have the components, let's consider the following method:
public static Object readContextMap(Context context,
String mapName, String mapKey, Integer mapValueIndex) throws Exception {
// gets Context class for inspection
Class<?> cls = context.getClass();
// search for a method based on supplied mapName
Method mapMethod = cls.getDeclaredMethod(mapName);
// get a value from the retrieved map based on mapKey
Object mapValue = mapMethod.getReturnType()
.getDeclaredMethod("get", Object.class)
.invoke(mapMethod.invoke(context), mapKey);
// if the result is of type list, use the index to return the indexed element
if (List.class.isAssignableFrom(mapValue.getClass())) {
return ((List<?>)mapValue).get(mapValueIndex);
}
// otherwise return the object itself
return mapValue;
}
For testing purposes, consider the following main method:
public static void main(String[] args) throws Exception {
Context context = new Context();
String input = "myMap.friends[0]";
// parse input into...
String mapName = "myMap";
String mapKey = "friends";
Integer valueIndex = 0;
Object firstFriend = readContextMap(context, mapName, mapKey, valueIndex);
System.out.println(firstFriend);
// prints Foo
Object name = readContextMap(context, "myMap", "name", null);
System.out.println(name);
// prints Blah
}
This should be approximately what you want. You can easily create variations of this to set values as well. Please bear in mind that this code is just for demo purposes and needs a better error handling (e.g. verify if the context is really returning a map and nothing else).
This should be something along the lines you are looking for.
There's no need to use reflection here. You can simply cast it (which is also unsafe, but less so).
You can just do this:
List<String> friends = (List<String>) myMap.get("friends");
friends.set(0, "Bob");

Getting NoFastSuchElementException, when I use valueMap() in gremlin query with java

GraphTraversal<Vertex, Map<String, Object>> tsList = traversalSource.V().has("request","id_key",114).valueMap();
while(tsList.hasNext())
{
System.out.println(tsList.next().get("status")); //prints result
System.out.println(tsList.next().get("tree_id_key")); //prints result
System.out.println(tsList.next().get("username")); //here throws Exception for any vertex.
System.out.println(tsList.next().get("tree_status"));
}
when I run the above query, I am getting values for any first and second propertyKey. but after getting answers for two Keys It throws NoFastSuchElementException for any propertyKey...Kindly help me..how can I resolve this?
but using below query I am able to get the answer:
GraphTraversal<Vertex, Map<String, Object>> tsList = traversalSource.V().has("request","id_key",114).values("status","tree_id_key","username","tree_status");
while(tsList.hasNext())
{
System.out.println(tsList.next());//prints "status" value
System.out.println(tsList.next());//prints "tree_id_key" value
System.out.println(tsList.next());//prints "username" value
System.out.println(tsList.next());//prints "tree_status" value
}
updated:
GraphTraversal<Vertex, Map<String, Object>> ts = traversalSource.V().has("request","id_key",113).valueMap();
while(ts.hasNext())
{
Map<String, Object> tsList=ts.next();
SuiteIdKey=(long)((ArrayList)tsList.get("suiteKey")).get(0);
seqe=(int)((ArrayList)tsList.get("sequence")).get(0);
}
In the above query, ts will return many rows and for each row I will get suiteIdkey,seqe..I am able to get the answer. But tsList is Map<>, it is not directly returning answer when I use like this =(long)tsList.get("suiteKey"), without ArrayList. Is it the correct way? Kindly help me.
You are asking for two different things in those two traversals. The first one with valueMap() asks that the vertex be converted to a Map, so you don't want to keep calling next() in that loop. Just do:
Map<String, List<Object>> m = traversalSource.V().has("request", "id_key", 114).
valueMap().next();
System.out.println(m.get("status").get(0));
System.out.println(m.get("tree_id_key").get(0));
System.out.println(m.get("username").get(0));
System.out.println(m.get("tree_status").get(0));
Keep in mind above that i'm assuming your traversal always returns one vertex...account for that otherwise if that is not true.
In your second traversal where you do values() you are asking Gremlin to convert grab the values of those specific properties on that vertex and stream them out and thus you need to iterate with multiple calls to next.
Note that typically returning the entire vertex object isn't a recommended practice. It is somewhat akin to SELECT * FROM table in SQL. It is better to get only the fields that you want to get which then gets rid of the ugly multi-property issue of Map<String, List<Object>>:
Map<String, Object> m = traversalSource.V().has("request", "id_key", 114).
project('s`,'tik', 'u', 'ts').
by('status').
by('tree_id_key').
by('username')
by('tree_status').
next();
System.out.println(m.get("s"));
System.out.println(m.get("tik"));
System.out.println(m.get("u"));
System.out.println(m.get("ts"));

Check value inside Map

I have a Map where I save values with the form NAME-GROUP.
Before doing some operations, I need to know if the Map contains a specific group,
for example: I need to check for values containing group1 like Mark-group1.
I'm trying to get it this way:
if (checkList.containsValue(group1)) {
exists = true;
}
I can't provide the name when searching because there could be diferent names with the same group.
But it isn't finding the value, as seems that this function just looks for the entire value string and not only for part of it.
So, there would be any way of achieving this, or would I need to change the way I'm focusing my code.
Update--
This is the looking of my Map:
Map<Integer, String> checkList = new HashMap<Integer, String>();
I load some values from a database and I set them into the Map:
if (c.moveToFirst()) {
int checkKey = 0;
do {
checkKey++;
checkList.put(checkKey, c.getString(c.getColumnIndex(TravelOrder.RELATION)));
}while(c.moveToNext());
}
The relation column, has values like: mark-group1, jerry-group1, lewis-group2, etc...
So, the Map will have a structure like [1, mark-group1], etc...
What I need is to check if there is any value inside the map that contains the string group1 for example, I don't care about the name, I just need to know if that group exists there.
If you want to check any value contain your string as a substring you have to do the following:
for (String value : yourMap.values()) {
if (value.contains(subString)) {
return true;
}
}
return false;
By the way if your values in the map are really have two different parts, i suggest to store them in a structure with two fields, so they can be easily searched.

Changing LinkedHashMapValues

Below is data from 2 linkedHashMaps:
valueMap: { y=9.0, c=2.0, m=3.0, x=2.0}
formulaMap: { y=null, ==null, m=null, *=null, x=null, +=null, c=null, -=null, (=null, )=null, /=null}
What I want to do is input the the values from the first map into the corresponding positions in the second map. Both maps take String,Double as parameters.
Here is my attempt so far:
for(Map.Entry<String,Double> entryNumber: valueMap.entrySet()){
double doubleOfValueMap = entryNumber.getValue();
for(String StringFromValueMap: strArray){
for(Map.Entry<String,Double> entryFormula: formulaMap.entrySet()){
String StringFromFormulaMap = entryFormula.toString();
if(StringFromFormulaMap.contains(StringFromValueMap)){
entryFormula.setValue(doubleOfValueMap);
}
}
}
}
The problem with doing this is that it will set all of the values i.e. y,m,x,c to the value of the last double. Iterating through the values won't work either as the values are normally in a different order those in the formulaMap. Ideally what I need is to say is if the string in formulaMap is the same as the string in valueMap, set the value in formulaMap to the same value as in valueMap.
Let me know if you have any ideas as to what I can do?
This is quite simple:
formulaMap.putAll(valueMap);
If your value map contains key which are not contained in formulaMap, and you don't want to alter the original, do:
final Map<String, Double> map = new LinkedHashMap<String, Double>(valueMap);
map.keySet().retainAll(formulaMap.keySet());
formulaMap.putAll(map);
Edit due to comment It appears the problem was not at all what I thought, so here goes:
// The result map
for (final String key: formulaMap.keySet()) {
map.put(formulaMap.get(key), valueMap.get(key));
// Either return the new map, or do:
valueMap.clear();
valueMap.putAll(map);
for(Map.Entry<String,Double> valueFormula: valueMap.entrySet()){
formulaMap.put(valueFormula.getKey(), valueFormula.value());
}

Comparing java variables and printing

Suppose , I have some variables as :
String x="abcd";
String y="qwert";
String z="mnvji";
and more...
I take an input from user.
If user inputs 'x' , I print that string i.e. I print "abcd"
If user inputs 'y' , I print "qwert" and so on...
Is there any way to do it without switches or ifs??
Thank you,friends, in advance.
You could create a map from input string to result. Initialize the map:
Map<String, String> map = new HashMap<String, String>();
map.put("x", "abcd");
map.put("y", "qwert");
map.put("z", "mnvji");
And when you want to print the result from the input from the user:
Scanner s = new Scanner(System.in);
while (s.hasNextLine())
System.out.println(map.get(s.nextLine()));
Local variable names aren't available at runtime and reading field knowing it's name requires some reflection (see #amit's answer). You need a map:
Map<String, String> map = new HashMap<>();
map.put("x", "abcd");
map.put("y", "qwert");
map.put("z", "mnvji");
Now just take value from that map:
String value = map.get(userInput);
value will be null if it doesn't match any of x/y/z.
As we can approach like that also,
String input[]=new String['z'];
input['X']="abcd";
input['Y']="qwert";
input['Z']="mnvji";
System.out.println(input['X']);
But it will come under some limitation
Map collection using key value pair implementation solve your problem .
put varible x,y,z as key and "abcd" ,.. as value.
Retrieve value from specific key according to input value.
Map<String, String> map = new HashMap<String, String>();
map.put("x", "abcd");
map.put("y", "qwert");
map.put("z", "mnvji");
to get value
String value = map .get(inputValue).
Map<String, String> map = new HashMap<>();
map.put("x", "abcd");
map.put("y", "qwert");
map.put("z", "mnvji");
Scanner s = new Scanner(System.in);
while (s.hasNextLine())
System.out.println(map.get(s.nextLine()));
will probably work.
Put your variable set into a HashMap as (key,value) pairs and just retrieve the value for the particular key when user inputs the key.
create an string array in which x,y,z should be indexes and store the content relatively ...
get the user input and pass it to the array as index ..you will get it..
If you really don't want to use switches or ifs (and I'd assume you include maps in that) then you'd have to use reflection to get the names of all the variables and decide which to print on them. Here's the basics:
Class yourClass = Class.forName("yourpackagename.YourClassName")
Field[] allFields = yourClass.getDeclaredFields();
String[] fieldNames = new String[allFields.length];
for(int i = 0; i < fieldNames.length; i++)
{
fieldNames[i] = allFields [i].getName();
}
//Get name of field user wants to display, and look it up in
//the fieldNames array to get the index of it, store this index
Object instance = yourClass.newInstance();
System.out.println(allFields[indexToDisplay].get(instance));
Of course, this could well be overkill.
If you have no choice but using object variables (fields) and not a Map as suggested by other answers - you might want to use reflection, and specifically the Class.getField() and Class.getDeclaredField() methods-
Field f = MyClass.class.getDeclaredField("x");
System.out.println(f.get(myObject));
Where MyClass is your class name and myObject is the object you want the value from.
Note that with this approach - you cannot add fields - you can only get existing ones.

Categories

Resources