[英]hashMap in Java
I wanna do that: Method will be deleteLeafValue where it will get Object value. 我想这样做:方法将是deleteLeafValue,它将在其中获取对象值。 This will search all the sub hashMap values and clear all items where third value is Object value. 这将搜索所有子hashMap值,并清除第三个值为Object值的所有项目。
public void put(K1 key1, K2 key2, V value)
{
HashMap<K2, V> childMap = get(key2);
if (childMap == null)
{
childMap = new HashMap<K2, V>();
put(key1, childMap);
}
childMap.put(key2, value);
}
How can i do deleteLeafValue method? 我该怎么办deleteLeafValue方法?
Do you mean? 你的意思是?
public void remove(K1 key1, K2 key2) {
Map<K2, V> childMap = get(key2);
if (childMap != null)
childMap.remove(key2);
}
or 要么
public void removeByValue(V value) {
for(Map<K2, V> childMap : values())
for(Iterator<V> valueIter = childMap.values(); valueIter.hasNext();)
if(valueIter.next().equals(value))
valueIter.remove();
}
You might find using a composite key is simpler 您可能会发现使用复合键更简单
Map<String, String> extendedMap = new HashMap<String, String>();
extendedMap.put("Row1/Column1", "French");
extendedMap.put ("Row1/Column2", "English");
extendedMap.put ("Row1/Column3", "Spanish");
extendedMap.put ("Row2/Column1", "John");
extendedMap.put ("Row2/Column2", "Richard");
extendedMap.put ("Row3/Column3", "Cole");
extendedMap.remove("Row3/Column3");
I don't think you should extend HashMap
, you should manage an existing Map implementation from the outside: 我不认为您应该扩展HashMap
,而应该从外部管理现有的Map实现:
Add the leaves 添加叶子
public static <V, K1, K2> V put(final Map<K1, Map<K2, V>> outerMap,
final K1 outerKey,
final K2 innerKey,
final V value){
Map<K2, V> innerMap = outerMap.get(outerKey);
if(innerMap == null){
innerMap = new HashMap<K2, V>();
innerMap.put(innerKey, value);
outerMap.put(outerKey, innerMap);
return null;
}
return innerMap.put(innerKey, value);
}
Delete leaves by value 按值删除叶子
/** Returns the number of deletions that were made */
public static <V, K1, K2> int deleteLeafValues(
final Map<K1, Map<K2, V>> outerMap,
final V value){
int deleted = 0;
for(final Map<K2, V> innerMap : outerMap.values()){
final Iterator<Entry<K2, V>> iterator =
innerMap.entrySet().iterator();
while(iterator.hasNext()){
if(iterator.next().getValue().equals(value)){
iterator.remove();
deleted++;
}
}
}
return deleted;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.