nahata5 nahata5 - 4 months ago 22
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").get("OrderID").add("1234H");
map.get("238991").get("OrderID").add("1233B");
map.get("238991").put("Name", new ArrayList<>());
map.get("238991").get("Name").add("Smith, John");
System.out.println(map.get("238991"));
System.out.println(map.get("238991").get("Name").get(0));


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

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.

Comments