我需要从函数返回一个HashMap的子集。那么什么是更好的方法或最有效的方法:什么是获取HashMap中元素子集的有效方法?
a。遍历HashMap的键,我的条件下取其下降,将它们添加到本地创建的HashMap并将其返回
或
湾克隆HashMap并使用retainAll
方法。
即:
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;
}
或
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;
}
或两者都最优化和有效?
当你知道你想迭代一个HashMap时,LinkedHashMap允许你迭代这些值 – Simon