简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM