tarekahf
tarekahf

Reputation: 1002

Define Java map of key String and value can be any type including a map

Is it possible to define a map object in Java where the key is a string and the value can be either a string, number, date, or another map?

Following is an example of what I'm trying to do:

Map<String,? super String> myMap1 = new HashMap<String, String>();
myMap1.put("streetAddress", "123 street name");
myMap2.put("city", "New York");

Map<String,? super String> myMap2 = new HashMap<String, Object>();
myMap2.put("name", "John Smith");
myMap2.put("age", 35);
myMap2.put("salary", 67000);
myMap2.put("dob", parseDate("1980-03-20"));
myMap2.put("address", myMap1);

The above will most likely result in a compile error, and I need help to be able to initialize such map.

My objective is to create a map object that can map a string key to a date, string, number, or another map. How is that possible?

Upvotes: 0

Views: 2214

Answers (1)

Ksu
Ksu

Reputation: 149

Try this:

    Map<String, String> myMap1 = new HashMap();
    myMap1.put("streetAddress", "123 street name");
    myMap1.put("city", "New York");

    Map<String, Object> myMap2 = new HashMap();
    myMap2.put("name", "John Smith");
    myMap2.put("age", 35);
    myMap2.put("salary", 67000);
    myMap2.put("dob", LocalDate.parse("1980-03-20"));
    myMap2.put("address", myMap1);

    System.out.println(myMap2.toString());//{address={streetAddress=123 street name, city=New York}, dob=1980-03-20, name=John Smith, salary=67000, age=35}

Map<String, Object> - key - String, value - any object

Upvotes: 4

Related Questions