Java 关于检查映射是否包含某个键
我有一个值patient id,它是我从应用程序后端获得的,如下所示Java 关于检查映射是否包含某个键,java,collections,Java,Collections,我有一个值patient id,它是我从应用程序后端获得的,如下所示 String PatientId = rxDetails.getPatient().getPatientID() ; //patient ID recieved from backend 下面是另一张存储详细信息的地图,如下所示 Map <String ,List<String>> m = new LinkedHashMap LinkedHashMap<String,List<Stri
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
如上所示,我必须首先提取ValidatedPatientList的所有键,然后比较它是否包含第一个患者id,请
建议如何实现这一点 使用HashMap#containsKey。如果映射包含指定键的映射,则返回true
Javadoc forjava.util.HashMap
/**
* 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;
}
/**
*如果此映射包含
*指定的密钥。
*
*@param key此映射中存在的密钥将被测试
*@如果此映射包含指定对象的映射,则返回true
*钥匙。
*/
公共布尔containsKey(对象键){
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
{...}
}
map将此链接添加到书签中,每当您想知道类必须如何使用以及它提供了什么方法时,请查看文档:if(validatedPatientList.containsKey(patientId)){}
@assylias非常感谢。。!!List List=validatedPatientList.get(patientId);如果(list!=null){//do something}这些基本相同,只是您必须明确检查是否存在键,即list
是否为null,但containsKey()返回一个布尔值,这是本例中的要求。@rahul非常感谢,如果(ValidatedPatientList!=null&&!ValidatedPatientList.isEmpty()&&(ValidatedPatientList.containsKey(patientId)){@rahulroc我想这也会差不多,也会奏效是的……这完全一样。为了更好地理解,我只是把它放在单独的if语句下
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
{...}
}