简体   繁体   中英

Java Fill nested HashMap

I have a problem. I created the following object:

HashMap<String, HashMap<String, HashMap<Integer, ArrayList<Slope>>>>
     usedSlopeList = new HashMap<>();

Then I have the following ArrayList<Slope> :

ArrayList<Slope> tempSlopeList = Slope.getSlopeList(
    agent, key, slope, startDateTimeWithExtraCandles);

But when I want to fill the usedSlopeList like this:

usedSlopeList.put("15m", 
new HashMap<String, HashMap<Integer, ArrayList<Slope>>>()
    .put("EMA15", new HashMap<Integer, ArrayList<Slope>>()
    .put(15, tempSlopeList)));

Unfortunately this gives me the error:

Required type: HashMap<Integer,java.util.ArrayList<com.company.models.Slope>>
Provided: ArrayList<Slope,

But I don't see why this is wrong... Can someone help me?

Map::put returns value while a map is expected.

That is, new HashMap<Integer, ArrayList<Slope>>().put(15, tempSlopeList) returns ArrayList<Slope> and so on.

The following code using Map.of available since Java 9 works fine:

usedSlopeList.put("15m", new HashMap<>(Map.of("EMA15", new HashMap<>(Map.of(15, tempSlopeList)))));

Update A cleaner solution not requiring Java 9 could be to implement a generic helper method which creates an instance of a HashMap and populates it with the given key/value:

static <K, V> HashMap<K, V> fillMap(K key, V val) {
    HashMap<K, V> map = new HashMap<>();
    map.put(key, val);
    return map;
}

ArrayList<Slope> tempSlopeList = new ArrayList<>(Collections.emptyList());
HashMap<String, HashMap<String, HashMap<Integer, ArrayList<Slope>>>>
     usedSlopeList2 = fillMap("15m", 
                          fillMap("EMA15", 
                              fillMap(15, tempSlopeList)
                          )
                      );
    
System.out.println(usedSlopeList2);    

Output:

{15m={EMA15={15=[]}}}

You used the new HashMap().put() as the second parameter in your code, which causes the issue.

HashMap().put is not a builder method; it doesn't return the hashmap. It returns the previous value associated with the key, which in your case is an ArrayList.

You have a map, which expects a string as key and a hashmap as value, but put() method doesn't return a hashmap, it return an V object(<K, V>), that is why you should create hashmap separately, add the object and than try to add it. Anyway i think you should reconsider your design.

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