开发者

How do I access individual values within a string array within a Hashmap?

开发者 https://www.devze.com 2023-03-07 02:38 出处:网络
My declaration of the map is as follows: Map<Integer, String[]> mapVar = new HashMap&开发者_运维知识库lt;Integer, String[]>();

My declaration of the map is as follows:

Map<Integer, String[]> mapVar = new HashMap&开发者_运维知识库lt;Integer, String[]>();

And I initialized it by making several string arrays and putting them into my map with a corresponding Integer.

I would like to then Iterate through all of the elements in my String array within the map. 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.

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.


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:

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 Strings associated with a particular key:

List<String> valuesFor1 = multimap.get(1);
0

精彩评论

暂无评论...
验证码 换一张
取 消