MultiValueMap get values - java

hi im trying to access a MultiValueMap which is in a Hashmap
this is my HashMap insideprojectDetails HashMap
private HashMap<String, ClassDetails> classDetailsMap = new HashMap<String, ClassDetails>();
inside that classDetailsMap i have MultiValueMap called methodDetailsMap
private MultiMap<String, MethodDetails> methodDetailsMap = new MultiValueMap<String, MethodDetails>();
when im trying to access the methodDetailsMap by
Set<String> methodNamesSet = projectDetails.getClassDetailsMap().get(cls).getMethodDetailsMap().keySet();
String[] methodNames = methodNamesSet.toArray(new String[0]);
for (int i = 0; i < methodNames.length; i++) {
String methodName = methodNames[i];
System.out.println(cls + " "+methodName);
//codes used to access key values
Collection coll = (Collection) methodNamesSet.get(methodName);
System.out.println(cls + " "+methodNamesSet.get(methodName));
}
i get a error get saying cannot resolve method get(java.lang.String)
is there any way to access the MultiValueMap

Its a compilation error with your code. There is no get method in Set.
methodNamesSet.get(methodName)
To get method details, first loop through the set and then get method details from methodDetailsMap as below.
MultiValueMap<String, MethodDetails> methodDetailsMap = projectDetails.getClassDetailsMap().get(0).getMethodDetailsMap();
Set<String> methodNamesSet = methodDetailsMap.keySet();
for(String str: methodNamesSet) {
System.out.println(methodDetailsMap.get(str));
}

I read your code and as I understand first you need to get all method names of cls class then you want to get them one by one. So in the for loop you need to get from the getMethodDetailsMap().This will help you:
for (int i = 0; i < methodNames.length; i++) {
String methodName = methodNames[i];
System.out.println(cls + " "+methodName);
//codes used to access key values
Collection coll = projectDetails.getClassDetailsMap().get(cls).getMethodDetailsMap().get(methodName);
System.out.println(cls + " "+methodNamesSet.get(methodName));
}

Related

How can I iterate over the results of a hash map where the value is a list?

I've created a hash map that groups unique keys that combine three parameters, i.e. customer, sc and admin. I want to create a unique list of keys with a list of servers attached. I've implemented the following:
public static void main(String[] args) {
String items = "customer1^sc1^admin1|server1~" +
"customer1^sc1^admin1|server2~" +
"customer1^sc1^admin1|server3~" +
"customer2^sc1^admin1|server1~" +
"customer3^sc1^admin1|server3~" +
"customer3^sc1^admin1|server2~";
// Set up raw data
List<String> splitItems = Arrays.asList(items.split("\\s*~\\s*"));
// Display raw data
System.out.println("Raw List: " + items);
// Create a hash map containing customer name as key and list of logs as value
HashMap<String, List<String>> customerHashMap = new HashMap<>();
// Loop through raw data
for (String item : splitItems) {
// Create new lists. One for customers and one for logs
// List<String> customerList = new ArrayList<>();
List<String> logList;
String list[] = item.split("\\|");
String customer = list[0];
String log = list[1];
logList = customerHashMap.get(customer);
if (logList == null){
logList = new ArrayList<>();
customerHashMap.put(customer, logList);
}
logList.add(log);
// System.out.println(logList);
}
// Print out of the final hash map. Customer "a" should only have "a" logs, customer "b" with "b", etc.
System.out.println("");
List<String> hashMapList = new ArrayList<String>();
Iterator it = customerHashMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
String output = pair.getKey() + "|" + pair.getValue().toString();
hashMapList.add(output);
it.remove();
}
String hashMapResultString = hashMapList.toString();
String hashMapResultFormatted = hashMapResultString.replaceAll("[\\[\\]]", "");
System.out.println(hashMapResultFormatted);
}
Raw List: customer1^sc1^admin1|server1~customer1^sc1^admin1|server2~customer1^sc1^admin1|server3~customer2^sc1^admin1|server1~customer3^sc1^admin1|server3~customer3^sc1^admin1|server2~
Hash Map String:
customer2^sc1^admin1|server1, customer3^sc1^admin1|server3, server2, customer1^sc1^admin1|server1, server2, server3
I now want to use the hash map to create a string which will be parsed further (don't ask lol). So I set the keys and values of the hash map to a string which separates them with a unique delimiter |. The problem is that because the key is a List<String>, when printing I can't ascertain the beginning of every new key if its value is a list with more than one item, i.e. customer3^sc1^admin1|server3, server2, is followed immediately by customer1^sc1^admin1|server1, server2, server3. I need a delimiter here that separates them.
My ideal output would look like this:
customer2^sc1^admin1|server1~customer3^sc1^admin1|server3, server2~customer1^sc1^admin1|server1, server2, server3~...
How can I achieve this?
Update:
This is the answer I ultimately found useful for my particular problem:
StringBuilder s = new StringBuilder();
for (Map.Entry<String, List<String>> entry : customerHashMap.entrySet()) {
s.append(entry.getKey() + "|");
List<String> list = entry.getValue();
for (String item : list) {
if (item != list.get(list.size() - 1)) {
s.append(item + "^");
} else {
s.append(item);
}
}
s.append("~");
}
System.out.println(s.toString());
You can iterate through a map's entry set:
StringBuilder s = new StringBuilder();
for(Map.Entry<String,List<String>> entry : map.entrySet()) {
s.append(entry.getKey() + "\n");
List<String> list = entry.getValue();
for(String item : list) {
s.append(" " + item + "\n");
}
}
return s.toString();
For the sake of a clearer example, I've output a different format from the one you asked for, but this illustrates how to work with a map of list values. When adapting to your needs, have a look at java.util.StringJoiner and the related Collectors.joining(); it may well be useful.
Streams can be handy here:
String encoded = map.entrySet().stream()
.map( entry -> entry.getValue().stream()
.collect(Collectors.joining("^"))
+ "|" + entry.getKey())
.collect(Collectors.joining("~"));
What happens here is:
We get a stream of Entry<String,List<String> out of the map
The lambda entry -> ... converts each entry into a string of the form val1^v2^v3^...^valN|key, i.e. we are mapping a Stream<Entry<>> into a Stream<String>.
the final collect() joins the stream of strings into a single string using ~ as a delimiter.

java assign map each value into an String array

I want to save data into master - details table.First portion is for master table and last portion is for details table.I have got java.lang.String cannot be cast to [Ljava.lang.String .How to recover from this problem.How to assign map.get("step_id[]") into a string array String[] WfIds. I want to assign each value into distinct string array.
Controller Code
Map<String,Object> wfManager = new HashMap<String,Object>();
//************************Master data sent from view******************************//
wfManager.put("workflow_code",(request.getParameter("workflow_code")).toUpperCase());
wfManager.put("workflow_name",request.getParameter("workflow_name"));
wfManager.put("workflow_descr",request.getParameter("workflow_descr"));
wfManager.put("object_type_code",request.getParameter("object_type_code"));
//*********************Detail item data sent from view********************************//
wfManager.put("wf_block_id[]", request.getParameter("wf_block_id[]"));
wfManager.put("step_code[]" , request.getParameter("step_code[]"));
wfManager.put("step_name[]", request.getParameter("step_name[]"));
wfManager.put("doa_type_code[]", request.getParameter("doa_type_code[]"));
wfManager.put("doa_type_name[]", request.getParameter("doa_type_name[]"));
Service Code
public Map<String, String> insert(Map<String, Object> map) {
//************************Master data sent from view******************************//
Map<String, String> data = new HashMap<String, String>();
Workflow wf = new Workflow();
wf.setWorkflowCode((String)map.get("workflow_code"));
wf.setWorkflowName((String)map.get("workflow_name"));
wf.setWorkflowDescr((String)map.get("workflow_descr"));
wf.setObjectTypeCode((String)map.get("object_type_code"));
String[] WfIds = (String[]) map.get("step_id[]");
String[] wfBlockIds = (String[]) map.get("wf_block_id[]");
String[] wfsCodes = (String[]) map.get("step_code[]");
String[] stepNames = (String[]) map.get("step_name[]");
String[] doaTypeCodes = (String[]) map.get("doa_type_code[]");
String[] doaTypeNames = (String[]) map.get("doa_type_name[]");
List<WorkflowDetails> wfDetailsList = new ArrayList<WorkflowDetails>();
for(int i = 0; i< wfsCodes.length; i++){
WorkflowDetails wfDetails = new WorkflowDetails();
wfDetails.setWorkflowCode(wf.getWorkflowCode());
wfDetails.setWorkflowName(wf.getWorkflowName());
wfDetails.setWorkflowDescr(wf.getWorkflowDescr());
wfDetails.setWorkflowObjectTypeCode(wf.getObjectTypeCode());
wfDetails.setWorkflowObjectTypeName(wf.getObjectTypeName());
wfDetailsList.add(i,wfDetails);
}
wf.setSteps(wfDetailsList);
id = workflowManagerDAO.insertDoc(wf);
data.put("id", id);
return data;
}
Code for DAO:
#Transactional
#Override
public String insertDoc(Workflow wfManager) {
for(int i = 0; i < wfManager.getSteps().size(); i++){
WorkflowDetails wfDetails = new WorkflowDetails();
wfDetails = wfManager.getSteps().get(i);
sessionfactory.getCurrentSession().save(wfDetails);
sessionfactory.getCurrentSession().flush();
}
String id = (String) sessionfactory.getCurrentSession().save(wfManager);
sessionfactory.getCurrentSession().flush();
return id;
}
If you absolutely need to use request.getParameter(), you will have to convert your arrays to strings using a delimiter character, e.g. convert this
String[] array = { "John", "Peter", "Paul" };
to this
String plainTextArray = "John#Peter#Paul";
Then you will be able to pass you array values as String (the only type that getParameter() understands).
You can then restore them like this
String[] restoredArray = request.getParameter("plainTextArray").split("#");
Maybe you want to have a look at setAttribute() and getAttribute() which let you store any objects (including arrays). You can start here Difference between getAttribute() and getParameter()

.asFormUrlEncoded() to retrieve data from hashMap<String, String>

I'm sending a video file along with some user details to my play framework application using MultipartRequest, the user details are added to a hashmap Map<String, String> myMap;on the server side I have retrieved my video file using .asMultipartFormData();
I was trying to retrieve my map using .asFormUrlEncoded(); but that uses Map<String, String[]>
So I've only been able to retrieve one value from my hash map, if I try to retrieve anymore using this code
for(int i =0; i < myMap.size(); i++){
String param = "param" + (i + 1);
System.out.println(myMap.get(param)[i]);
}
I get an arrayOutOfBounds error, is there an alternative solution to retrieve the data from the MultipartFormData, or can I implement my loop differently?
maybe I shouldn't be using .asFormUrlEncoded();at all to retrieve the hashmap?
EDIT
I've modifed my code to use an iterator
Iterator<String> myVeryOwnIterator = myMap.keySet().iterator();
while(myVeryOwnIterator.hasNext()) {
String key=(String)myVeryOwnIterator.next();
String[] value= myMap.get(key);
System.out.println(key + " " + value);
}
This prints my key, but returns Ljava.lang.String;# for the values, I think this is because the .asFormUrlEncoded(); is expecting a <String, string[]>, but my hashMap uses <String, String> any solution to this?
This was the solution:
Iterator<String> myVeryOwnIterator = myMap.keySet().iterator();
while(myVeryOwnIterator.hasNext()) {
String key=(String)myVeryOwnIterator.next();
String[] value= myMap.get(key);
System.out.println(key + " " + value[0]);
}

how to insert multiple values of an attribute into mongoDB using java with Map?

I am writing a java code to insert form values into mongoDB using java code. I am using map to retrieve all the values from the map and inserting it into mongoDB. However, if an attribute is having multiple values, it is only inserting only one value. My code is:
Map<String, String[]> articleData = request.getParameterMap();
for(String key : articleData.keySet())
{
for(int i=0; i<articleData.get(key).length;i++)
{
document.put(key,articleData.get(key)[i]);
}
}
table.insert(document);
However, right now, it is overriding the values of the attribute having multiple values.
How can I resolve it?
Try this, It will give you a basic idea. Adjust code according to your program:
Map<String, String[]> articleData = request.getParameterMap();
for(String key : articleData.keySet())
{
BasicDBObject data =new BasicDBObject();
for(int i=0; i<articleData.get(key).length;i++)
{
data.put("",articleData.get(key)[i]);
}
document.put(key,data);
}
table.insert(document);
Encode a JSON object .
Try this out.
Map<String, String[]> articleData = request.getParameterMap();
for(String key : articleData.keySet())
{
JSONObject out = new JSONObject();
out.put("key", key);
out.put("value", articleData.get(key));
System.out.println(out);
}
dbobj.put("multiple",out);
collection.insert(dbobj);

Importing a map in javax.scripting javascript environment

I'm seeing some odd behavior in the javax.scripting map implementation.
The online examples show an example of adding to a list within the js environment:
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
List<String> namesList = new ArrayList<String>();
namesList.add("Jill");
namesList.add("Bob");
namesList.add("Laureen");
namesList.add("Ed");
jsEngine.put("namesListKey", namesList);
System.out.println("Executing in script environment...");
try
{
jsEngine.eval("var names = namesListKey.toArray();" + "for(x in names) {" + " println(names[x]);" + "}"
+ "namesListKey.add(\"Dana\");");
} catch (ScriptException ex)
{
ex.printStackTrace();
}
System.out.println(namesList);
However, if you try to do something similar with a map, you see odd behavior. For one thing, if you try to iterate through the map keys, e.g.
HashMap<String, Object> m = new HashMap<String, Object>();
jsEngine.put("map", m);
There's no way to obtain the map keys - if you try to iterate through the keys, you get method names-
jsEngine.eval(" for (var k in m.keySet()){ println(k)};");
results in :
notifyAll
removeAll
containsAll
contains
empty
equals
...
In the js context you can address values in the map with m.get(key) but not with m[key], and if the key doesn't exist it throws an error. Can anyone shed some light on this behavior, or is it just broken? Thanks.
for..in in JavaScript is not the same thing as for..each in Java, even though they look similar. for..in in JavaScript iterates over the property names in an object. The method names are exposed to Rhino as properties on the native Java HashMap object, just as if you had the following JavaScript object:
{
notifyAll:function(){},
removeAll:function(){},
containsAll:function(){},
contains:function(){},
empty:function(){},
equals:function(){}
}
My recommendation is that you either convert the HashMap keyset to an array, using method Set.toArray, or you obtain an iterator using Set.iterator(). Here's a short Rhino script showing how you may accomplish this using the toArray method:
x=new java.util.HashMap();
x.put("foo","bar");
x.put("bat","bif");
x.put("barf","boo");
var keyArray = x.keySet().toArray();
for(var i=0, l = keyArray.length; i < l; i++){
var key = keyArray[i];
var value = x.get(key);
print(value);
}
Which outputs:
bif
bar
boo
Here's how you can do the same thing using Set.iterator:
x=new java.util.HashMap();
x.put("foo","bar");
x.put("bat","bif");
x.put("barf","boo");
var keyIter = x.keySet().iterator();
while(keyIter.hasNext()){
var key = keyIter.next()
var value = x.get(key);
print(value);
}
If you convert java.util.Map to a native object, your JavaScript will be cleaner:
final Map<String,String> javaMap = new HashMap<>();
javaMap.put("alpha", "bravo");
javaMap.put("charlie", "delta");
final NativeObject jsMap = new NativeObject();
for (Map.Entry<String,String> entry : javaMap.entrySet()) {
jsMap.defineProperty(
entry.getKey(), entry.getValue(), NativeObject.READONLY
);
}
final ScriptEngine jsEngine =
(new ScriptEngineManager()).getEngineByName("JavaScript");
jsEngine.put("map", jsMap);
jsEngine.eval(
"for (var idx in map) print(idx + '; ' + map[idx] + '\\n');"
);
Otherwise, you're stuck with standard Java syntax.

Categories

Resources