2012-10-18 29 views
0

Hash哈希如何把新的和更新當前

private Map<String, List<MEventDto>> mEventsMap; 

然後,我要檢查如果鍵已經存在。如果存在,我將只更新這些值,然後我將添加一個新的密鑰。我怎樣才能做到這一點。

我嘗試像:

for (MEventDto mEventDto : mEventList) { 
    String mEventKey = mEventDto.getMEventKey(); 
    String findBaseMEvent = mEventKey.split("_")[0]; 

    if (mEventsMap.get(findBaseMEvent) != null) { 
     // create new one 
     mEventsMap.put(findBaseMEvent , mEventDtoList); 
    } else { 
     // just update it 
     mediationEventsMap. 
    } 
} 

我怎樣才能做到這一點與Hash

+0

檢出: - [Map#containsKey](http://docs.oracle.com/javase/7/docs/api/java/util/Map.html#containsKey(java.lang.Object)) –

回答

1

您可以使用Map#containsKey來檢查按鍵是否存在或不存在: -

所以,你的情況,這將是這樣的: -

if (mEventsMap.containsKey(findBaseMEvent)) { 
     // just update the enclosed list 
     mEventsMap.get(findBaseMEvent).add("Whatever you want");    
} else { 
     // create new entry 
     mEventsMap.put(findBaseMEvent , mEventDtoList); 
} 
0

HashMap containsKey()您可以使用此方法

boolean containsKey(Object key) 
     Returns true if this map contains a mapping for the specified key. 
0

如下你會做到這一點:

String mEventKey = mEventDto.getMEventKey(); 
String findBaseMEvent = mEventKey.split("_")[0]; 

List<MEventDto> list = mEventsMap.get(findBaseMEvent); 
/* 
* If the key is not already present, create new list, 
* otherwise use the list corresponding to the key. 
*/ 
list = (list == null) ? new ArrayList<MEventDto>() : list; 

// Add the current Dto to the list and put it in the map. 
list.add(mEventDto); 
mEventsMap.put(findBaseMEvent , mEventDtoList);