Android hashMapValues 如何获取值并格式化

Android hashMapValues how to get value and format it

如何打印我的 HashMap 的值:

String hashMapValues = PHOTO_IDS.get(所有值);

hashMapValues 输出为: id1, id2, id3, id4, id5

HashMap<String,String> PHOTO_IDS;

onCreate....
PHOTO_IDS = new HashMap<String, String>();

if(vc.readLAST_TAKEN_PIC().equals("imageCam1")) { PHOTO_IDS.put("imageCam1", id); }
                   else if(vc.readLAST_TAKEN_PIC().equals("imageCam2")) { PHOTO_IDS.put("imageCam2", id); }
                   else if(vc.readLAST_TAKEN_PIC().equals("imageCam3")) { PHOTO_IDS.put("imageCam3", id); }
                   else if(vc.readLAST_TAKEN_PIC().equals("imageCam4")) { PHOTO_IDS.put("imageCam4", id); }
                   else if(vc.readLAST_TAKEN_PIC().equals("imageCam5")) { PHOTO_IDS.put("imageCam5", id); }

非常感谢您的帮助。

UPDATED_____________________________________________

谢谢大家的回复。这是工作代码:

String hashmapValues = PHOTO_IDS.values().toString();
TMP_PHOTO_ID = hashmapValues.replaceAll("[\[\]]", "");

您可以使用 entrySet() 打印所有值,如下所示:

更新:使用StringBuilder

StringBuilder s = new StringBuilder();
for(Entry<String,String> e : PHOTO_IDS.entrySet()){
   s.append(e.getValue() + ", ");
}
String result = s.toString();

参考HashMap#entrySet() java documentation了解更多信息。

还有一种方法可以直接获取逗号分隔值,如下所示:

String result = PHOTO_IDS.values().toString();

但这将 return 输出为 [id1, id2, id3, id4, id5],因此您只需要删除那些括号 [],您可以使用 substring[= 轻松完成18=]

您可以使用 Map.getValues() 来达到这个目的。

喜欢

System.out.println(PHOTO_IDS .values());

输出会像

[id1, id2, id3, id4, id5]

这里你需要从字符串中替换 [] 个字符。

如果您不想在值列表两边加上括号,您可以执行以下操作。但是对于所有解决方案,如果您担心顺序,您可能需要考虑使用 LinkedHashMap

StringBuilder sb = new StringBuilder();
for(String val : map.values()){
    sb.append(val+",");
}
String result = sb.toString();
System.out.println(result.substring(0, result.length() - 1)); //This will remove the last comma.