哈希如何推送新的和更新当前

时间:2012-10-18 11:39:58

标签: java hash

我有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

执行此操作

3 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:0)

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

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

答案 2 :(得分: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);