Reputation: 25
Is it possible to populate hashmap like this?
final HashMap<String, String> map = new HashMap<>();
map.put("path", path);
map.put("tableName", "table");
map.put("fileType", fileType);
final HashMap<String, String> option = new HashMap<>();
map.put("option", option.put("header", "true"));
Or is there another right (or better) way than this? because when I try to print "map" the key "option" has no value in it.
Thanks in advance
Upvotes: 1
Views: 1511
Reputation: 81
HashMap<String ,Object> data= new HashMap<>();
data.put("post",myPost);
data.put("username",userName);
data.put("date" ,date);
You can use different data types with HashMap in android studio-java
Upvotes: 1
Reputation: 6117
You can store data this way:
public static void main(String[] args){
Map<String, String> dataMap = new HashMap<>();
dataMap.put("key1", "Hello");
dataMap.put("key2", "Hello2");
Map<String, Object> map = new HashMap<>();
map.put("1", 1);
map.put("2", dataMap);
map.put("3", "Value3");
Object obj = map.get("1");
printData(obj);
Object obj2 = map.get("2");
printData(obj2);
Object obj3 = map.get("3");
printData(obj3);
}
private static void printData(Object obj) {
if (obj instanceof Integer) {
Integer integer =convertInstanceOfObject(obj, Integer.class);
System.out.println(integer);
}else if( obj instanceof HashMap){
HashMap<String, String> resMap = convertInstanceOfObject(obj, HashMap.class);
System.out.println(resMap);
}else if( obj instanceof String ){
String data = convertInstanceOfObject(obj, String.class);
System.out.println(data);
}
}
public static <T> T convertInstanceOfObject(Object o, Class<T> clazz) {
try {
return clazz.cast(o);
} catch(ClassCastException e) {
return null;
}
}
Output:
1
{key1=Hello, key2=Hello2}
Value3
map
type is Map<String, Object>
because its value can be any type of Object
Upvotes: 2
Reputation: 517
You can't do this , you have to specify the datatype properly,
final HashMap<String, String> map = new HashMap<>();
map.put("path", path); //path has to be a variable pointing to a string
map.put("tableName", "table");
map.put("fileType", fileType); // filetype has to be a variable pointing to a string
final HashMap<String, String> option = new HashMap<>();
map.put("option", option.put("header", "true")); //this is wrong
HashMap<String,Map<String,String>> option = new HashMap<String,HashMap<String,String>>();
option.put("Key",map);
example: Creating and populating the maps
Map<String, Map<String, Value>> outerMap = new HashMap<String, HashMap<String, Value>>();
Map<String, Value> innerMap = new HashMap<String, Value>();
innerMap.put("innerKey", new Value());
Storing a map
outerMap.put("key", innerMap);
Retrieving a map and its values
Map<String, Value> map = outerMap.get("key");
Value value = map.get("innerKey");
Upvotes: 2