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");
}
Related
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);
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"
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());
}
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];
I am getting the below error when I compile the below code
Enumeration e = bean.getSession().getAttributeNames();
while (e.hasMoreElements()) {
String name = (String)e.nextElement();
String value = session.getAttribute(name).toString();
System.out.println(name + " = " + value);
Error:
found : java.util.Iterator
required: java.util.Enumeration
Enumeration e = bean.getSession().getAttributeNames();
You shouldn't be using an enumeration, it should be an Iterator. Then use the methods of the Iterator like hasNext() to check if there is a next item and next() to get the next item. Hope it helps :)
how about just using a for loop?
for (String name : bean.getSession().getAttributeNames() ) {
String value = session.getAttribute(name).toString();
System.out.println( name + " = " + value );
}
It looks like you're actually using a getAttributeNames() method that return an instance of java.util.Iterator. So as a quick fix, this should work:
Iterator it = bean.getSession().getAttributeNames();
while (it.hasNext()) {
String name = (String)it.next();
String value = session.getAttribute(name).toString();
System.out.println(name + " = " + value);
More help/info could be provided if we knew the actual types of the bean variable and/or the return value of bean.getSession().
I think the problem is in the first line. This works for me:
<%
Enumeration attrs = session.getAttributeNames(); //you will need to include java.util.Enumeration
while(attrs.hasMoreElements()){ //for each item in the session array
String id = attrs.nextElement().toString(); //the name of the attribute
out.print("'" + id + "': '" + session.getAttribute(id) + "'"); //print out the key/value pair
}
%>
As others pointed out though, you should be using an Iterator