Building a nested HashMap - java

I want to build a nested hashmap in java like this
{Customer:
{
Area:{}
}
Bank:
{
City:{}
}
}
How can i do this?

The easiest way is to use a map as the value of your outer map, like the following:
Map<String, Map<String, String>> nestedMap = new HashMap<> ();
Map<String, String> fooInnerMap = new HashMap<> (), barInnerMap = new HashMap<> ();
nestedMap.put ("foo", fooInnerMap);
nestedMap.put ("bar", barInnerMap);
However, this is not really convenient to use. If you want better answers, please specify what you want and what you tried.
Your data structure, for example, looks like JSON. If you need your Map to save or exchange data, you could use a JSON library.

Related

How can I combine two HashMap objects containing the different types?

I have two HashMap objects defined as:
Map<String, String> requestParams = new HashMap<>();
Map<String, Boolean> requestParamForOauth = new HashMap<>();
How can I merge these two maps?
Assuming that both maps contain the same set of keys, and that you want to "combine" the values, the thing you would be looking for is a Pair class, see here for example.
You simply iterate one of the maps; and retrieve values from both maps; and create a Pair; and push that in your result map.
The only downside is that there is no "official" Pair class that you could use (see here for more thoughts around that).
Alternatively, if there is a "deeper" meaning of those "combined" values (beyond a simple "tuple/pair" semantics), you could instead create your own class that wraps around those two values.
Your keys are of the same type (String), but the values are not even related by an interface or super class, you will need to define a Map<String, Object> and make use of the Map#putAll method
Map<String, String> requestParams = new HashMap<>();
Map<String, Boolean> requestParamForOauth = new HashMap<>();
Map<String, Object> requestParamForOauth2 = new HashMap<>();
requestParamForOauth2.putAll(requestParams);
requestParamForOauth2.putAll(requestParamForOauth);
If you want to use one list to store all the data You can
use one HashMap<String,Object>
What do you want to do when the same key appears in both Map? If you want to keep both the String and Boolean, then you'll need a map that looks like this: Map<String, Pair(String, Boolean)>. If you just want to keep one value, then Map<String, Object> is what you want.

Casting a HashMap

i´m trying to make a casting of Hasmap
I have this hasmap:
Map<String, Object> requestargs = new Map<String, Object>();
Other side i have a method who bring me a hashmap of: Map<String, Document>
MultipartForm form = MgnlContext.getWebContext().getPostedForm();
The method is getDocuments();
I need to put the return of this method in my hashmap making something like this:
requestargs = form.getDocuments();
But i don´t know how to cast this Hasmap og (String,Document) to (String,Object)
Thanks
Unless you can use a wildcard
Map<String, ? extends Object> requestargs
You will need to copy the map into a new map:
requestargs = new HashMap<String, Object>(form.getDocuments());
The two types are not related directly. Were you able to make the assignment directly (or via casting) it would be possible to insert a value with non-Document type into the map, and that would be type-unsafe:
Map<String, Document> docs = form.getDocuments();
Map<String, Object> requestargs = docs; // not actually allowed
requestargs.put("Foo", new Object());
for (Document doc : docs.values()) {
// doc isn't necessarily a Document! ClassCastExceptions abound.
}
To prevent this problem happening, such an assignment is forbidden by the type system.
The wildcard works because it makes it impossible to call put on the map, since there is no way to know what types can be put into the map safely.

Converting Map<String,String> to Map<String,Object>

I have Two Maps
Map<String, String> filterMap
Map<String, Object> filterMapObj
What I need is I would like to convert that Map<String, String> to Map<String, Object>.
Here I am using the code
if (filterMap != null) {
for (Entry<String, String> entry : filterMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
Object objectVal = (Object)value;
filterMapObj.put(key, objectVal);
}
}
It works fine, Is there any other ways by which I can do this without iterating through all the entries in the Map.
Instead of writing your own loop that calls put, you can putAll, which does the same thing:
filterMapObj.putAll(filterMap);
(See the Javadoc.)
And as Asanka Siriwardena points out in his/her answer, if your plan is to populate filterMapObj immediately after creating it, then you can use the constructor that does that automatically:
filterMapObj = new HashMap<>(filterMap);
But to be clear, the above are more-or-less equivalent to iterating over the map's elements: it will make your code cleaner, but if your reason for not wanting to iterate over the elements is actually a performance concern (e.g., if your map is enormous), then it's not likely to help you. Another possibility is to write:
filterMapObj = Collections.<String, Object>unmodifiableMap(filterMap);
which creates an unmodifiable "view" of filterMap. That's more restrictive, of course, in that it won't let you modify filterMapObj and filterMap independently. (filterMapObj can't be modified, and any modifications to filterMap will affect filterMapObj as well.)
You can use the wildcard operator for this.
Define filterMapObj as Map<String, ? extends Object> filterMapObj and you can directly assign the filterMap to it. You can learn about generics wildcard operator
You can simply write
Map<String, Object> filterMapObj = new HashMap<>(filterMap);
You can use putAll method to solve the problem.The Object is the father class of all objects,so you can use putAll without convert.

How Can I create a generic HashMap to insert collections and objects?

How Can I instantiate a HashMap to put collections and objects?.
//it's wrong
Map<String,?>params=new HashMap<String,? >
List<Person> lstperson=getPerson();
params.put("person",lstperson);
params.put("doc",objectDoc);
params.put("idSol",new Long(5));
service.method(params);
//method
public void method(Map<String, ?> params);
Declare the hash map as
Map<String,Object> params = new HashMap<String,Object>();
You can keep the declaration of
public void method(Map<String, ?> params);
as it is, as long as the method only every tries to read from the map.
All classes in Java extends Object. so you can use Object for a value type in a map, like
Map<String, Object> params = new HashMap<String, Object>
You need to change
Map<String,?>params=new HashMap<String,? >
to like this
Map<String,Object>params=new HashMap<String,Object>()
But its not good practice to put all type of objects into single map. Better you can create POJO and add it to map.
I cam here for substitute in Kotlin
You can declare in kotlin as :-
val map: Map<String, Any?>

Java creating instance of a map object

Really simple question hopefully. I want to do something like this:
Map<String, String> temp = { colName, data };
Where colName, data are string variables.
Thanks.
Map is an interface. Create an instance of one the classes that implements it:
Map<String, String> temp = new HashMap<String, String>();
temp.put(colName, data);
Or, in Java 7:
Map<String, String> temp = new HashMap<>();
temp.put(colName, data);
#JohnGirata is correct.
If you're REALLY upset, you could have a look here http://nileshbansal.blogspot.com.au/2009/04/initializing-java-maps-inline.html
It's not quite what you're asking, but is a neat trick/hack non the less.
The quick way of putting entries in a Map just created is the following (let me use a HashMap 'cause I like them):
Map<String,String> temp = new HashMap<String,String>(){{
put(colName, data);
}};
Note all those parenthesis with a closing semicolon!
While it's true that in Java7 you can generally use the diamond operator and write something like this Map<String,String> temp = new HashMap<String,String>();, this does not work when putting elements in the Map inline. In other words, the compiler with yell at you if you try the following (don't ask me why):
Map<String,String> temp = new HashMap<>(){{
put(colName, data);
}};

Categories