build Uri string into name-value collection in java - 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"

Related

How to decode String to a corresponding Map?

I am new to Java. I have a problem that, I need to Implement the decode(String) method that decodes a String to a corresponding Map. In the assignment, the requirements are like this,
Empty keys and values are allowed, but the equals sign must be present (e.g. "=value", "key=").
If the key or value is empty, empty String should be returned.
If the given String is empty, an empty Map should be returned.
If the given String is null, null should be returned.
Sample Input: one=1&two=2
Should return a Map containing {"one": "1", "two": "2"}
Map<String, String> map = new HashMap<>();
map.put("One", "1");
map.put("Two", "2");
map.put("", "");
map.put("Key", "");
map.put("", "Value");
Set<String> keys = map.keySet();
for(String key : keys) {
System.out.print("\"" + key + "\"" + ":" + "\"" + map.get(key) + "\"");
}
My piece of code is giving output as required, But I have implemented this in the main method with Map<K, V> interface, while I need to write code that takes String as a parameter and decodes to Map.
Thanks
One solution could be:
public Map<String, String> parseMap(String mapString) {
if (mapString == null || mapString.isEmpty()) {
return Collections.emptyMap();
}
return Arrays.stream(mapString.split("&"))
.map(this::splitParam)
.collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));
}
public AbstractMap.SimpleEntry<String, String> splitParam(String it) {
final int idx = it.indexOf("=");
final String key = it.substring(0, idx);
final String value = it.substring(idx + 1);
return new AbstractMap.SimpleEntry<>(key, value);
}
usage
String inputString = "one=1&two=2";
Map<String, String> map = parseMap(inputString);
//your code to print the map again
Set<String> keys = map.keySet();
for(String key : keys) {
System.out.print("\"" + key + "\"" + ":" + "\"" + map.get(key) + "\"");
}
try this in your editor, just 4 lines :)
String input = "one=1&two=2";
String[] kvs = input.split("&");
Map<String, String> hashMap = Stream.of(kvs)
.collect(Collectors.toMap(item -> item.split("=")[0],
item -> item.split("=")[1]));
hashMap.forEach((k, v) -> System.out.println(k + ":" + v));

Parse the string response using key value pair and add them in map or array

I am getting a response which has key value pairs separated by :
USER: 0xbb492894B403BF08e9181e42B07f76814b10FEdc
IP: 10.0.2.6
NETMASK: 255.255.0.0
SUPERNODE: tlcsupernode.ddns.net
PORT: 5000
COMMUNITY: tlcnet
PSK: mysecret
MAC: 00:02:ff:00:02:06
To parse and store them, I am using the below code:
Map<String, String> map = new HashMap<String, String>();
String[] parts = response.trim().split(":");
for (int i = 0; i < parts.length; i += 2) {
map.put(parts[i], parts[i + 1]);
}
for (String s : map.keySet()) {
System.out.println(s + " is " + map.get(s));
Log.d("Testing", " "+s + " is " + map.get(s));
}
But as the MAC has multiple times : separator, I am not able to parse it properly.
I got the help from the below link:
Split string into key-value pairs
Using Java 8 streams, you can do it as a one liner.
String resp = "USER: 0xbb492894B403BF08e9181e42B07f76814b10FEdc\n" +
"IP: 10.0.2.6\n" +
"NETMASK: 255.255.0.0\n" +
"SUPERNODE: tlcsupernode.ddns.net\n" +
"PORT: 5000\n" +
"COMMUNITY: tlcnet\n" +
"PSK: mysecret\n" +
"MAC: 00:02:ff:00:02:06";
Map<String, String> map = Arrays.asList(resp.split("\\R")).stream().map(x -> x.split(":", 2)).collect(Collectors.toMap(x -> x[0], x -> x[1].trim()));
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(String.format("Key: %s, Value: %s", entry.getKey(), entry.getValue()));
}
Prints,
Key: SUPERNODE, Value: tlcsupernode.ddns.net
Key: NETMASK, Value: 255.255.0.0
Key: COMMUNITY, Value: tlcnet
Key: PORT, Value: 5000
Key: IP, Value: 10.0.2.6
Key: PSK, Value: mysecret
Key: USER, Value: 0xbb492894B403BF08e9181e42B07f76814b10FEdc
Key: MAC, Value: 00:02:ff:00:02:06
Here, \\R (matches any type of newline) splits your response string with newline which further gets split using : with second parameter as 2 to split the string to get max two values, and finally gets collected as Map using Collectors.toMap
Edit:
For older version of Java, you can use a simple for loop,
String resp = "USER: 0xbb492894B403BF08e9181e42B07f76814b10FEdc\n" + "IP: 10.0.2.6\n" + "NETMASK: 255.255.0.0\n"
+ "SUPERNODE: tlcsupernode.ddns.net\n" + "PORT: 5000\n" + "COMMUNITY: tlcnet\n" + "PSK: mysecret\n"
+ "MAC: 00:02:ff:00:02:06";
Map<String, String> map = new HashMap<>();
for (String line : resp.split("\\R")) {
String[] keyValue = line.split(":", 2);
map.put(keyValue[0], keyValue[1]);
}
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(String.format("Key: %s, Value: %s", entry.getKey(), entry.getValue()));
}
Instead of
String[] parts = response.trim().split(":");
Do this:
String[] parts = response.trim().split(":", 2);
That 2 at the end will force the string to be split into only two substrings. Using no additional parameter like you're doing currently means "split into an unlimited number of substrings".
Also, you should trim the keys and values before storing them in case there are spaces around the initial ':'
One caveat: This assumes that the additional ':' characters will always occur in the value, and not in the key.
See here for more details.
You can just change your split regex to :\\s|\\n. With this the code you are using should work as expected.
Another solution is to split by \\R first and handle each line separately. For this you either can use line.split(":", 2) or line.split(":\\s"). If you need a more flexible solution you can use a regex to process each line.
Pattern pattern = Pattern.compile("(?<key>.+):\\s+(?<value>.+)");
Map<String, String> map = new HashMap<>();
for (String line : response.split("\\R")) {
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
map.put(matcher.group("key"), matcher.group("value"));
}
}
For Java 8 and above you can use the Stream API:
Pattern pattern = Pattern.compile("(?<key>.+):\\s+(?<value>.+)");
Map<String, String> map2 = Arrays.stream(response.split("\\R"))
.map(pattern::matcher)
.filter(Matcher::find)
.collect(Collectors.toMap(m -> m.group("key"), m -> m.group("value")));
The combination of colon followed by whitespace does seem to be unique, at least in the sample data you showed us. So, try splitting on that:
String[] parts = response.split(":\\s+");
map.put(parts[0], parts[1]);

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);

Java hashmap iterate only certain keys

I'm looking for a way to get the values for just a specific key when I get into the second loop here. I'm using snakeyaml and loading it to a Map. My yaml looks something like this:
number:
id: status.number
label: Number
contactType:
id: status.contact_type
label: Contact Type
What I'm attempting to do is just get the key and value for id. It's probably super obvious, but I haven't found a way to do so.
Map<String, Map<String, String>> a = (Map<String, Map<String, String>>) yaml.load(input);
for (Map.Entry<String, Map<String, String>> t : a.entrySet()) {
String key = t.getKey();
for (Map.Entry<String, String> e : t.getValue().entrySet()) {
System.out.println("OuterKey: " + key + " InnerKey: " + e.getKey() + " VALUE:" + e.getValue());
}
}
To get the value(s) for the "inner key", you don't need to loop through every inner map.
In the following example, I assume you already have an innerKey variable that holds the desired inner key.
Map<String, Map<String, String>> a = (Map<String, Map<String, String>>) yaml.load(input);
for (Map.Entry<String, Map<String, String>> t : a.entrySet()) {
String outerKey = t.getKey();
String innerValue = t.getValue().get(innerKey);
System.out.println("OuterKey: " + outerKey + " InnerKey: " + innerKey + " VALUE:" + innerValue);
}

Request.getParameterMap values not castable to string

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];

Categories

Resources