1

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

4
  • What are your inputs, expected outputs, and actual outputs? Commented May 20, 2011 at 15:00
  • The strings "13", "26" and "14", "28" I get [Ljava.lang.String;@342798e7 and [Ljava.lang.String;@13a78071 Commented May 20, 2011 at 15:02
  • That's the default toString() representation of a String[]. You want to print the individual Strings, not the array object's toString(). See my answer. Commented May 20, 2011 at 15:04
  • before you go all happy building a datastructure with hashmaps and arrays only, consider creating classes for the data you want to hold with appropriate implementations of hashCode and equals Commented May 20, 2011 at 16:29

4 Answers 4

3

Try

for (String[] value : mapvar.values()) {
   System.out.println(Arrays.toString(value));
}
Sign up to request clarification or add additional context in comments.

Comments

3
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.

Comments

1
for (Map.Entry<Integer, String[]> entry : mapVar.entrySet()) {
   for (String s : entry.getValue()) {
      // do whatever
   }
}

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.