Request.getParameterMap values not castable to string - java

i am trying to get the complete parameter map from the request object and iterate over it.
here is the sample code
Map map = request.getParameterMap();
for(Object key : map.keySet()){
String keyStr = (String)key;
Object value = map.get(keyStr);
System.out.println("Key " + (String)key + " : " + value);
}
output
Key businessunit : [Ljava.lang.String;#388f8321
Key site : [Ljava.lang.String;#55ea0889
Key startDate : [Ljava.lang.String;#77d6866f
Key submit : [Ljava.lang.String;#25141ee0
Key traffictype : [Ljava.lang.String;#4bf71724
its evident from the output that the value object is an instance of String
now when i change my code to something like this
Map map = request.getParameterMap();
for(Object key : map.keySet()){
String keyStr = (String)key;
Object value = map.get(keyStr);
if(value instanceof String)
System.out.println("Key " + (String)key + " : " + (String)value);
}
it prints nothing but as per the previous output it should have printed the values and if i remove instanceOf check it gives ClassCastException. is this the expected behavior or i am doing something wrong here ?

[Ljava.lang.String;#XXXXXXX means it is array of String not a single String. So your condition fails and it does not print anything.

As the object which is returned is an array of strings as Harry Joy pointed out, you will have to use the Arrays.toString() method in order to convert that array to a printable string:
Map map = request.getParameterMap();
for (Object key: map.keySet())
{
String keyStr = (String)key;
String[] value = (String[])map.get(keyStr);
System.out.println("Key" + (String)key + " : " + Arrays.toString(value));
}

The value is an array. If you're sure that the array is not empty, you should get the string value like this:
String value = (String) map.get(keyStr)[0];

Related

How to print all the keys and values in a map to a single string?

I have written the following code:
String reqParams = null;
Map<String, String[]> params = request.getParameterMap();
for (Object key : params.keySet()) {
String keyStr = (String) key;
String[] value = params.get(keyStr);
reqParams = reqParams + ((String) key + "=" + Arrays.toString(value) + " ");
}
System.out.println(reqParams);
I have the following output:
nullorderId=[01] orderStatus=[delivered]
How can I get rid of the null that prints at the beginning?
Is it possible to avoid the [ ] from printing?
How can I do this using streams?
Use map operation and the joining collector:
String resultSet =
params.entrySet()
.stream()
.map(e -> e.getKey() + "=" + String.join(", ", e.getValue()))
.collect(Collectors.joining(" "));
", " is the delimiter if the array has more than one element.
" " in the joining is the delimiter to separate the elements
from the source.
Initialize reqParams as an empty string. That is,
String reqParams = null;
becomes
String reqParams = "";
Initialize reqParams like this : String reqParams = "" or don't append your string to redParams and just do this reqParams = ((String) key + "=" + value[0] + " ");
Just get the element in the array instead of turning the array into a String: reqParams = reqParams + ((String) key + "=" + value[0] + " ");
You could stream params.keySet().stream().forEach(key -> .... ) and add a function in the forEach that appends the key and the value to a String like you're doing in the for loop.
You could use the join method of the String class to turn the array into a String, avoiding the [ ] characters. Also, you don't need all the casting and extra parentheses that you have in your original code, if you use Map.Entry with type parameters, and iterate through the entry set instead of the key set.
for( Map.Entry<String,String[]> entry : params.entrySet()) {
reqParams = reqParams + entry.getKey() + "=" + String.join(",", entry.getValue()) + " ";
}
So here, join takes your array and separates all the elements with commas.
Lastly, if you initialise reqParams to "" instead of null, then the word null won't print.
String reqParams = "";

How to obtain particular value from Map in a "String" format

I have a Map :
Map<String, String> value
How to obtain particular value "String" ----> "type" from json value, how do i obtain it?
I tried below code, which only returns me KEY and not VALUE
Iterator it = payload.entrySet().iterator();
while (it.hasNext())
{
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
String key = pair.getKey().toString();
String value = pair.getValue().toString();
Log.d("getActionValue", "key : " + key);
Log.d("getActionValue", "value : + value");
}
You don't access your variable in your output, since value is still in in the string.
Change like this:
Log.d("getActionValue", "value : " + value);
Your problem is here Log.d("getActionValue", "value : + value"); it should be Log.d("getActionValue", "value : "+ value);
Try this for loop :-
for (Map.Entry<String, String> entry : payload.entrySet())
{
Log.d("getActionValue", "key : " + entry.getKey());
Log.d("getActionValue", "value :" + entry.getValue());
}
I want that particular "String" ----> "type" from value, how do i
obtain it?
payload Map contains JSONObject's as value of every key. so to get type need to first convert String to JSONObject then get value using type key:
JSONObject jsonObject=new JSONObject(value);
String strType="";
if(jsonObject.has("notification-action")){
JSONObject jsonObjectnotification=jsonObject.optJSONObject
(""notification-action"");
if(jsonObjectnotification.has("type")){
strType=jsonObjectnotification.optString("type");
}
}
You logging it wrong.
Should be:
Log.d("getActionValue", "value : " + value);

build Uri string into name-value collection in java

HashMap<String, List<String>> filterableMap = new HashMap<>();
filterableMap.put("department", Arrays.asList("A","B",null));
filterableMap.put("group", Arrays.asList("C","D",null));
From the above map i need to dynamically build a queryString like show below.
"SomeURL"/token/filter?department=A&department=B&group=C&group=D
I just used Hashmap we can use any thing as long as we can hold the values in name value pair.
for (Map.Entry<String, List<String>> entry : filterableMap.entrySet()) {
String key = entry.getKey();
List<String> value = entry.getValue();
for(String aString : value){
System.out.println("key : " + key + " value : " + aString);
if("department".equalsIgnoreCase(key)) {
qStrBulderBuilder.append("department =");
qStrBulderBuilder.append(value);
}
}
}
I am using like above approach , but i need to make sure i need put "=" and "&" in the right places some times we may not get "department" or "group"

Hashtable content : the first 2 Keys are Null .... How to get my saved content

I have a problem with my hashtable... I have a hashtable< String1,String2 > String1 = is a JTextfield as my Hashtable Key
String2 = is a JTextArea as my Hashtable content
myHashtable.put(JTextfield.getText(),JTextArea.getText());
and now I want to write all my saved content from my Hashtable into a file
but my first 2 contents are "null"
for (int i = 0; i < myHashtable.size(); i++) {
String[] key = myHashtable.keySet().toString().split(", ");
writer.println(key[i].replace("]", "").replace("[", "") + ": "
+ myHashtable.get(key[i]));
the following output should looks like:
examplekey : some content
examplekey2 : more content
examplekey3 : some content
but it looks like:
examplekey : null
examplekey2 : null
examplekey3 : some content
the reason why I write it so, is that I want to read this file, to get my Hashtable content after a restart and the .keySet function gives me a "[" and "]" at the start and end thats why I replace this with "".
You should run your program through a debugger to better understand what it is doing.
Let's follow an example:
Hashtable<String, String> myHashtable = new Hashtable<>();
myHashtable.put("1", "rat");
myHashtable.put("2", "cat");
myHashtable.put("3", "bat");
Running your loop, the first iteration will go like this:
myHashtable.keySet().toString() -> "[3, 2, 1]"
String[] key = myHashtable.keySet().toString().split(", ") -> "[3", "2", "1]"
key[0] -> "[3"
key[0].replace("]", "").replace("[", "") -> "3"
myHashtable.get(key[0]) -> myHashtable.get("[3") -> null
As you can see, replace() returns a new string with the replacement in place of the target. It does not modify the original string. So when you call myHashtable.get(key[0]) the key is "[3", which is not in the hashtable, so it returns null. If you run your code with the example hashtable you will get something like this in your file:
3: null
2: cat
1: null
It works for the keys in the middle, "2" in the example, because when you split the string they already don't have a "[" or "]" attached to them.
Now, notice that when you do myHashtable.keySet().toString().split(", ") you already have access to the elements in the keyset. You don't have to convert it to a string and then try to get the keys from this string. So you can do:
for (String key : myHashtable.keySet()) {
writer.println(key + ": " + myHashtable.get(key));
}
We can make it a bit faster if we iterate over all entries directly:
for (Map.Entry<String, String> entry : myHashtable.entrySet()) {
writer.out.println(entry.getKey() + ": " + entry.getValue());
}

retrieve values after iteration

After iterating over a "hashmap list", I want to write the values into a string as 'value 1' and 'value 2'. I cannot figure how?Can someone help me!
for (Object listItem : (List)value) {
System.out.println(key + ":" + listItem);
I have 2 values in my data. The above code gives me
Con:Name
Con:ID
Now, I want 'Name' to be value 1 and 'ID' to be value 2 so that I can replace and write them in the following string
"xxxxxxxxxx"+key+"xxxx"+value 1+"xxxxxxxxx"+value 2+"xxxxxxxxxx";
Try:
String value1="";
String value2="";
int counter=0;
for (Object listItem : (List)value) {
System.out.println(key + ":" + listItem);
if(counter==0) {//first pass assign value to value1
value1=listItem;
counter++;//increment for next pass
}else if(counter==1) {//second pass assign value to value2
value2=listItem;
counter++;//so we dont keep re-assigning listItem for further iterations
}
}
System.out.println(value1);//should display 'Name'
System.out.println(value2);//should display 'ID'
Using the StringBuilder class (assuming key is defined outside of the loop)
StringBuilder sb = new StringBuilder("xxxxxx" + key + "xxxx");
for (Object listItem : (List)value) {
System.out.println(key + ":" + listItem);
sb.append(listItem+"xxxxxxxxx");
}

Categories

Resources