Fast way to maintain hashmap with objects to avoid dupplicates

Nilanka Manoj :

I implemented following example code to reduce memory and time complexity of creating new complex object. It works faster than initial duplicates method in both complexities. My implementation is like follows:

public class ComplexObject{
    //set of heavy maps and lists
    public ComplexObject(int id, String param1, String param2){
        //init set of maps - this costs higher process time
    }
}
public class Test {
    Map<String,ComplexObject> complexObjectMap= new HashMap<>();
    public ComplexObject addObject(int id, String param1, String param2){
        if(complexObjectMap.containsKey(id + param1 + param2)){
            return complexObjectMap.get(id + param1 + param2);
        }
        else{
            ComplexObject complexObject = new ComplexObject(id, param1, param2);
            complexObjectMap.put(id+param1+param2,complexObject);
            return complexObject;
        }
    }
}

Can this be further optimized? in both complexities. Entirely different approach is also acceptable.

Vadeesha Rajapakshe :

You can do something to improve check availability and put by referring to Most efficient way to increment a Map value in Java

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=27700&siteId=1