简体   繁体   中英

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?

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.

The answer is probably no.

I say "probably" because this:

System.out.println(map.get("238991").get("Name").toString());

will print:

[Smith, John]

This works because the ArrayList.toString() method will format the list. However, that is probably not what you want because:

  • there are square brackets around the name, and
  • the if you have more than one element in the list you will get all of them; eg

     map.get("238991").get("Name").add("Jones, Barry"); [Smith, John, Jones, Barry] 

You should work with POJOs. Create a class that coveres your needs is much more feasible.

main.class

import java.util.ArrayList;
import java.util.HashMap;

public class OwnClass {

    public static void main(String[] args) {
        HashMap<String, Order> map = new HashMap<>();
        ArrayList<String> orderItems = new ArrayList<>();
        orderItems.add("1234H");
        orderItems.add("1234B");
        map.putIfAbsent("238991", new Order("Smith, John", orderItems));


        map.get("238991").addOrder("1234J");

        System.out.println(map);
    }
}

Order.class

import java.util.ArrayList;

public class Order {

    private String customer;
    private ArrayList<String> items;

    public Order(String string, ArrayList<String> orderItems) {
        this.customer = string;
        this.items = orderItems;
    }

    @Override
    public String toString() {
        return "Customer " + customer + " ordered " + items;
    }

    public void addOrder(String string) {
        items.add(string);
    }

}

Output:

{238991=Customer Smith, John ordered [1234H, 1234B, 1234J]}
import java.util.*;

public class MapReceivesListOrString{

public static void main(String []args){

   boolean shouldAddList = true;

   Map<String, Object> map = new HashMap<String, Object>(); //Creating a HashMap Polymorphically
   List<String> list = new ArrayList<>();

   list.add("1234H");
   list.add("1233B");

   String code1 = "some code one";
   String code2 = "some code two";

   if (shouldAddList) { // Your business logic whether to add a list or a string
       map.put("OrderID", list);        
   } else {
       map.put("code1", code1);
       map.put("code2", code2);
   }

   for (Map.Entry<String, Object> mapValues : map.entrySet()) { // Iterate over many list's or many string's
       Object value = mapValues.getValue();

       if (value instanceof List) {
            ArrayList myList = (ArrayList) value;

           System.out.println("List value one: " + list.get(0));
           System.out.println("List value two: " + list.get(1));
       } else {
           System.out.println("String value: " + value.toString());
       }
   }
}

}

Based on the existance of java generics we should define a specific type eg <String, ArrayList> rather than <String, Object> nonetheless it is a completely valid syntax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM