我有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 :(得分: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);