nahata5 nahata5 - 1 year ago 132
Java Question

Java HashMap with nested String or ArrayList

New to Java and was curious if there was a way to make the Value of a HashMap either a string or an ArrayList:

HashMap<String, HashMap<String, ArrayList<String>>> map = new HashMap<String, HashMap<String, ArrayList<String>>>();
map.putIfAbsent("238991", new HashMap<String, ArrayList<String>>());
map.get("238991").put("OrderID", new ArrayList<>());
map.get("238991").put("Name", new ArrayList<>());
map.get("238991").get("Name").add("Smith, John");

I would prefer to only add a String if I can for the Name rather than just accessing the first element of the list. Is this possible?

Answer Source

You should create a POJO, and use it as the HashMap value. It can contain all the data you need. Writing "pythonic" code in Java is just as bad, as doing it the other way around.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download