0

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?

3 Answers 3

1

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=[]}}}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, very easy solution for me!
1

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.

2 Comments

Then what could I use to create a filled hashmap?
If you don't have an other map with the values then you can't inline them. You have to create a new variable and fill them up manually.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.