关于检查Map是否包含某个键

时间:2013-01-05 12:29:33

标签: java collections

我有一个有价值的患者ID,我在申请中从后端获得,如下所示

 String PatientId = rxDetails.getPatient().getPatientID() ; //patient ID recieved from backend

这是另一个存储详细信息的地图,如下所示

 Map <String ,List<String>> m = new LinkedHashMap LinkedHashMap<String,List<String>>();
  List<String> info = new ArrayList<String>();
                info.add("ScriptInfo");
                info.add("Name");
                info.add("PhoneNo");
  m.put(PatientID ,info);
  transaction.setValue(ITransaction.PATIENT_DETAILS_FOR_CCV, ppvdetails);//please ignore this line as it is my framework dependent and in this line I am storing the Map

如图所示,它还存储了patientId

现在我的疑问是我必须在certian条件下交叉检查我从后端获得的患者ID是第一个已经准备就绪 是否存在于地图m中

现在如下图所示,我在另一个名为ValidatedPatientList的地图中引用了Map m。

Map ValidatedPatientList = (LinkedHashMap)transaction.getValue(ITransaction.VALIDATED_CCV_PH_NBR);//please ignore this line as it is my framework dependent and in this line I am retreving the Mao
if(ValidatedPatientList != null && !ValidatedPatientList.isEmpty())
      {
       Iterator iterator = ValidatedPatientList.keySet().iterator();
          if(iterator.hasNext())
          {

如上所示现在我必须首先提取ValidatedPatientList的所有键,然后必须比较它是否包含第一个患者ID,请 建议如何实现这个.. !!

1 个答案:

答案 0 :(得分:1)

使用HashMap#containsKey。如果映射包含指定键的映射,它将返回true。

java.util.HashMap

的Javadoc
/**
 * Returns <tt>true</tt> if this map contains a mapping for the
 * specified key.
 *
 * @param   key   The key whose presence in this map is to be tested
 * @return <tt>true</tt> if this map contains a mapping for the specified
 * key.
 */
public boolean containsKey(Object key) {
    return getEntry(key) != null;
}

代码示例:

Map<String ,List<String ValidatedPatientList = (LinkedHashMap<String ,List<String)transaction.getValue(ITransaction.VALIDATED_CCV_PH_NBR);
if(ValidatedPatientList != null && !ValidatedPatientList.isEmpty())
{  
   if (validatedPatientList.containsKey(patientId)) //returns true if map contains the key
   {...}
}