[英]How do I access individual values within a string array within a Hashmap?
My declaration of the map is as follows: 我对地图的声明如下:
Map<Integer, String[]> mapVar = new HashMap<Integer, String[]>();
And I initialized it by making several string arrays and putting them into my map with a corresponding Integer. 然后通过创建几个字符串数组并将其与相应的Integer放入我的地图中来对其进行初始化。
I would like to then Iterate through all of the elements in my String array within the map. 然后,我想遍历地图中String数组中的所有元素。 I tried these two possiblities but they're not giving me the right values:
我尝试了以下两种可能性,但它们没有给我正确的价值:
for(int ii =0; ii < 2; ii++)
System.out.println(((HashMap<Integer, String[]>)mapVar).values().toArray()[ii].toString());
and 和
mapVar.values().toString();
I also know the array and Integer are going into the map fine, I just don't know how to access them. 我也知道数组和Integer可以很好地进入映射,但我只是不知道如何访问它们。
Thanks 谢谢
Try 尝试
for (String[] value : mapvar.values()) {
System.out.println(Arrays.toString(value));
}
for (String[] strings : mapVar.values()) {
for (String str : strings) {
System.out.println(str);
}
}
That will print all of the Strings
in all of the arrays in the Map
. 这将打印
Map
中所有数组中的所有Strings
。
for (Map.Entry<Integer, String[]> entry : mapVar.entrySet()) {
for (String s : entry.getValue()) {
// do whatever
}
}
If you want to be able to access all the String
values in the map as one unit rather than dealing with the intermediate arrays, I'd suggest using a Guava Multimap : 如果您希望能够以一个单位访问映射中的所有
String
值,而不是处理中间数组,建议您使用Guava Multimap :
ListMultimap<Integer, String> multimap = ArrayListMultimap.create();
// put stuff in the multimap
for (String string : multimap.values()) { ... } // all strings in the multimap
Of course you can also access the list of String
s associated with a particular key: 当然,您也可以访问与特定键关联的
String
列表:
List<String> valuesFor1 = multimap.get(1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.