Although I agree with other commentators that I prefer to create suitable classes for your domain objects, we can simplify the syntax of building a map using some helper methods:
Map<String, Object> map = map( entry("student1", map( entry("name", "Tim"), entry("scores", map( entry("math", 10), entry("physics", 20), entry("Computers", 30) )), entry("place", "Miami"), entry("ranking", array(2, 8, 1, 13)) )), entry("student2", map(
You just need to define a helper class, as shown below, and use static import:
import static com.example.MapHelper.*;
Helper class:
package com.example; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MapHelper { public static class Entry { private String key; private Object value; public Entry(String key, Object value) { this.key = key; this.value = value; } public String getKey() { return key; } public Object getValue() { return value; } } public static Map<String, Object> map(Entry... entries) { Map<String, Object> map = new HashMap<String, Object>(); for (Entry e : entries) { map.put(e.getKey(), e.getValue()); } return map; } public static Entry entry(String k, Object v) { return new Entry(k, v); } public static List<Object> array(Object... items) { List<Object> list = new ArrayList<Object>(items.length); for (int i = 0; i < items.length; i++) { list.add(i, items[i]); } return list; } }
source share