In a filter function, I am trying to make a separate copy of a hashmap and remove some null
elements from the original, however finally when I print the copyhashmap the same elements are removed from it too while I only want it to happen for the original one and the copy should stays unchanged.
This is my code;
def filter(log){
Map logCopy = [:]
logCopy.putAll((log))
def indexedLog = logCopy.keySet()
for(def i = 0; i <indexedLog.size(); i++){
def subIndexedLog = logCopy[indexedLog[i]]
def subIndexedLogEntrySet = subIndexedLog.keySet();
for(def j = 0; j <subIndexedLog.size(); j++){
if(subIndexedLog[subIndexedLogEntrySet[j]] == null){
log[indexedLog[i]].remove(subIndexedLogEntrySet[j])
}
}
}
println logCopy
println log
return log;
}
def log = [letters:[a: null, b: null, c: "c"], numbers: [1: null, 2: null, 3: 3]]
filter(log)
Output;
[letters:[b:null, c:c], numbers:[2:null, 3:3]]
[letters:[b:null, c:c], numbers:[2:null, 3:3]]
I am so confused that when a null element is removed from log
in the loop, why the same element is also removed from logCopy, and why b
which indeed have a null
value is not removed. Please help me with this problem, and also if you can suggest a better solution than my filter()
function please do so. Thanks.