What is going on in this map / string array? - java

First, my code works fine. Nothing needs to be done, but as I copied some parts of the code from somewhere else, I dont fully understand whats happening here and hope for an explanation to learn something.
I use the play framework and send my controller class an AJAX POST with an ID and a score. I put those parameters into strings and save them in my DB.
Map<String, String[]> parameters = request().body().asFormUrlEncoded();
String questionIDInput = parameters.get("questionID")[0];
String voteScoreInput = parameters.get("score")[0];
The part I dont get is this: .get("questionID")[0]; / .get("score")[0];.
Why are the two zeros in there? Is the map some sort of a long String and I am using "questionID / score" as a key to find the values? The 0 really confuses me, enlighten me please.

parameters.get("questionID") returns the value for the key "questionID". The value is a String array (String[]), so parameters.get("questionID")[0] gives you the first String of that array.
Note that this code assumes that the "questionID" key is present in the Map and that the value for that key is a non empty array. If any of those assumptions would turn out to be false, you'll get a NullPointerException or ArrayIndexOutOfBoundsException.

The Map has a key and a value that corresponds to the key.
In your map, the key is of type String, whereas the value is of type String[] (an array of String object).
When you do parameters.get("questionID"), this will fetch the String[] array which corresponds to the key with value equal to "questionId".
In order to get the first element of the returned array, [0] is used.

Related

A special case of accessing parameters from servlet where they are encrypted and contain &,= value

I need to implement a URL which looks something like below one. The Notable thing is that its only one parameter i need to access and the value that's supposed to be held by the parameter is encrypted which may contains characters like & and =.
Example 1.
www.abc.com/disp?v=qww78agd=
The parameter v in above url contains value qww78agd=.
Supposing the encryption turns out the following way.
Example 2.
www.abc.com/disp?v=qww7&f=iuy68=
www.abc.com/disp?v=qww7&f==iuy68=
Then servlet will take v and f as two separate parameters, whereas i want to obatain qww7&f==iuy68= from parameter.
I thought of taking up all key value pairs from request HashMap and concatenating the joints via & and =. But the problem is that two consecutive = signs as in second case of example 2, its treated as only one equal to in request key,value map. Hence, my other = sign(s) are lost.
Is there any way such that i can get query string part as it is on my servlet and parse it using string processing on my own?
or any other approach?
It was easy.
Using the request.getQueryString() method the query string portion is fetched as it is as string on the servlet which I processed using my own logic of string processing.

Storing multiple values with same key in HashMap

I had an interview today and my interviewer asked me that how can I store multiple values having the same key in HashMap?
She gave me this example-->If I am given a list of String and I am suppose to store the length of String as key and the String itself as value.
I gave her the following solution in how I will be using HashMap:
Map<Integer, ArrayList<String>> map = new HashMap<Integer, ArrayList<String>>();
Integer being the length of the String and the ArrayList will store the Strings of that particular length.
The interviewer said that this is one way of using the HashMap but there is another way in which I won't be requiring ArrayList or any other data structure. During interview, I couldn't come up with any solution and now after enough googling, I still have nothing. Can anyone tell me how can I achieve the solution to this question?
Thanks!
One way without using ANY DATA STRUCTURE is concatenating all strings in values.
For e.g.
map.put(2,"rr*tt*yy");
map.put(3,"nnn*ggg*sss");
map.put(4,"ffff*dddd*jjjj");
May be the interviewer was looking to check if you know the 3rd party APIs or not.
There are multiple APIs available to do this.
Some of them can be found at
http://java.dzone.com/articles/hashmap-%E2%80%93-single-key-and
One option is every time you want to insert a record into the map, get the length of the String, salt then encrypt the size of the String to use as the key. BAM: you have a (fairly) unique retrievable key for each String without having to much around with String concatenation.
Just make sure you use a reversible encryption algorithm.
Another option would be to generate out a UUID and concatenate the size of the string to that.
UUID uuid = UUID.randomUUID()
String key = stringSize + "," + uuid;
This will also result in a unique value that you can retrieve later using String.split();

How can I use a map for calculations?

I'm working on a program for class. Using a TreeMap to store IDs (String - Key) and earnings amounts (double - value). I'm importing the values from a text file using a Scanner. My problem at the moment is that I need the values to accumulate rather than overwriting with the last value read. So my question is how do you use a Map to do calculations like that? Any help would be appreciated.
There is no implicit functionality in Map. Idea behind your homework assignment is for you to learn how to insert, find, get and replace to/from a Map. There are functions for each of these and ou should use all to get this done.
When adding a new value to your map, if the key already exists, you can get the associated value, add the new value to it, and put it back into the map. Example:
// Assuming that key and value were read from your file, and that
// myMap is declared as "Map<String, Double>"
if (myMap.containsKey (key)) {
double oldValue = myMap.get (key);
value += oldValue;
}
myMap.put (key, value);
1) Check whether value with same key exists in the map
2) If it exists then read it and add the currently read value. Put it back into map

problem getting value from HashMap

Hi all I'm using a HashMap to hold one of my object with a string key. when I put an object with a key it has no problem, when I put my second object I got my object added but can't get it with its key. Somewhat it goes to somewhere that is "next". I took a screenshot from debug mode (eclipse), below
although size shows 2, I can't see my second item in hashmap, but in other hashmap's next node.
To note something I use my key like in a form "name.tag", tag and name in same time can never be the same, but "tag" can be the same. does hashmap has something to do with dot operator when evaluating keys? I hope I could write clearly,
Thanks in advance
Edit:
Here is a piece of code I use to create my hashmap
private HashMap<String,ParameterItem> parseParametersNode(DataModel parent,Element element){
NodeList parameterChilds=element.getChildNodes();//gep element parameters
HashMap<String, ParameterItem> parameterItems=new HashMap<String, ParameterItem>();
for(int i=0;i<parameterChilds.getLength();i++){
if(parameterChilds.item(i).getNodeType()==Node.ELEMENT_NODE){
Element el=(Element) parameterChilds.item(i);
NamedNodeMap atts=el.getAttributes();
ParameterItem item=new ParameterItem();
for(int j=0;j<atts.getLength();j++){
Attr attribute=(Attr) atts.item(j);
String attributeValue=attribute.getValue();
String attributeName=attribute.getName();
item.setParsedProperty(attributeName, attributeValue);
} /*check attributes later*/
//finish loop and insert paramitem to params
String key="key"+i;
if(item.getTag()!=null && item.getName()!=null)
key=item.getName()+"."+item.getTag();
parameterItems.put(key, item);
// testParam=item;
// parameterItems.put(key, testParam);
}
}
return parameterItems;
}
There is not really a problem here: you have a hash collision. That is, both of your keys have been placed in the same hash bucket. It appears you have only four buckets (odd, I thought the initial default was 10 or 16), so the chance of that with random data is 25 percent. Your size incremented just fine. The next is the internal implementation’s way of pointing to the next element in the same bucket. If the number of elements in each buckets gets too big, Java will internally rehash into more buckets.
I do not see why you need a HashTable here since you are numbering your keys consecutively (you could use an ArrayList), but maybe this is just starter code and your real use case is different.
You have the code:
String key="key"+i;
but right after this you set key again not adding to it:
if(item.getTag()!=null && item.getName()!=null)
key=item.getName()+"."+item.getTag();
Should this be key +=item.getName()+"."+item.getTag(); ?

match the label and get value from Labelvaluebean

I'm getting a list of organization type and code are stored as labelvaluebean as below:
[LabelValueBean[ORG1, XX], [ORG2, AA]] - in array.
later these values are stored in a session variable. My question is, is there a way I can search thru this array to match the name and get the code ? (for ex: match with ORG1 and get XX). If user enter ORG1, I should send XX to back-end.
This sounds like you want to be using a Map instead of an array. A Map will store...mappings...between keys and values - think of it like a table with 2 columns, where the first column is your organization type and the second column is the code. You then take an organization code, look in your table at the values in the first column until you find a match, then you look over at the second column for the code, and return it. Obviously, this is handled by the Map implementation used, so all you need to do is declare what Objects should be used as the keys and values. In your case, maybe you'll have a Map<String, String>.
For example,
Map<String, String> map = new HashMap<String, String>();
map.put("ORG1", "XX");
map.put("ORG2", "AA");
map.get("ORG1") // returns "XX"
map.get("ORG2") // returns "AA"

Categories