I need to return a subset of HashMap from a function. So what is a better approach or the most efficient one:
a. Iterate over the HashMap keys and whichever falls under my conditions, add them to a locally created HashMap and return it
or
b. Clone the HashMap and use retainAll
method.
i.e.:
private HashMap<Long, List<Files>> abc(HashMap<Long, List<Files> mainMap, Set<Long> setNeeded){
HashMap<Long, List<Files>> retVal = new HashMap<Long, List<Files>>(mainMap);
for(Long timeStamp : mainMap.keySet()){
if(setNeeded.contains(timeStamp){
retVal.put(timeStamp, mainMap.get(key));
}
}
return retVal;
}
or
private HashMap<Long, List<Files>> abc(HashMap<Long, List<Files> mainMap, Set<Long> setNeeded){
HashMap<Long, List<Files>> retVal = new HashMap<Long, List<Files>>(mainMap);
retVal.retainAll(setNeeded);
return retVal;
}
or are both optimized and efficient ?