-1

I have this :

HashMap<String, String[]> strs = new HashMap<String, String[]>(); 
String [] morning_food = new String [8];
String [] snack1_food = new String [6];
String [] lunch_food = new String [12];
String [] snack2_food = new String [4];
String [] nite_food = new String [10];

strs.put("Breakfast", morning_food);
strs.put("Snack1", snack1_food);
strs.put("Lunch", lunch_food);
strs.put("Snack2", snack2_food);
strs.put("Dinner", nite_food);

How to get the content of strs? I want to print out or display it into Log. Thx

Michelle
  • 842
  • 3
  • 11
  • 19
  • 2
    I see this questions lacks research, because data from a `HashMap` can be retrieved with a key, which is the first parameter of the put method, and you use the get method with the key value to retrieve data... – Alvin Baena Nov 03 '11 at 12:41
  • [This has been answered elsewhere](http://stackoverflow.com/questions/1066589/java-iterate-through-hashmap/1066607#1066607) – Mr. S Nov 03 '11 at 12:41
  • mine is String [], the object is array, it is different problem should be >_ – Michelle Nov 03 '11 at 14:26

3 Answers3

1

strs.toString() ?

OR

You can:

for (String[] vals : strs.values()) {
    for (String val : vals) {
        System.out.print(val);
    }
}
Simeon
  • 7,582
  • 15
  • 64
  • 101
  • both of them, it is not display the content of String [] morning_food = new String [8]; String [] snack1_food = new String [6]; String [] lunch_food = new String [12]; String [] snack2_food = new String [4]; String [] nite_food = new String [10]; – Michelle Nov 03 '11 at 16:35
0

strs.toString() will return the content of the map as a String. It will delegate to the default toString of the arrays, which won't print anything useful, though. So you should use a List instead of a String[] as the value type of the map:

Map<String, List<String>> strs = new HashMap<String, List<String>>(); 
strs.put("Breakfast", new ArrayList<String>());
...

Collections should generally be preferred over arrays, in most of the cases.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • so where I should put this String [] morning_food = new String [8]; String [] snack1_food = new String [6]; String [] lunch_food = new String [12]; String [] snack2_food = new String [4]; String [] nite_food = new String [10]; so they are relating ? – Michelle Nov 03 '11 at 14:30
  • You don't put it anywhere. A list has a dynamic size. Once you add something to it, its size will automatically be incremented. Read the javadoc: it's a core class that must be known. – JB Nizet Nov 03 '11 at 15:29
0
String[] str-new String[strs.size()];
Set set=strs.keySet();
for(int i=0;i<strs.size();i++){
str[i]=strs.get(set.get(i));
}

Here str array will contain all the values.else you can directly use strs.get(set.get(i)).

Android Killer
  • 18,174
  • 13
  • 67
  • 90