A. Vreeswijk
A. Vreeswijk

Reputation: 954

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?

Upvotes: 0

Views: 130

Answers (3)

Nowhere Man
Nowhere Man

Reputation: 19565

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=[]}}}

Upvotes: 1

user10992464
user10992464

Reputation:

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.

Upvotes: 1

Dragos Ionut
Dragos Ionut

Reputation: 257

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.

Upvotes: 0

Related Questions