0

In the following code I'm using a String array as a HashMap value corresponding to a single key. The get() method of HashMap is returning the whole array. What if I want single value of array. (Say) I want only 'Lion' corresponding to key 'Animal'.

class HMTest{
  public static void main(String[] args){
     HashMap<String, String[]> subjects = new HashMap<String, String[]>();
     subjects.put("Fruit",new String[] {"mango","orange"});
     subjects.put("Animal",new String[] {"Lion","Tiger"});

     for(String s:subjects.get("Animal"))
       System.out.println(s);
     }
  }

I also tried replacing above for loop something like this

for(String[] s:subjects.get("Animal"))
       System.out.println(s[0]); 

But its giving me error.

Anybody please help me out.

4 Answers 4

4

Should be:

System.out.println(subjects.get("Animal")[0]);

The value of the "Animal" key is an array, not a String. Therefore, when you get("Animal"), you expect the value to be an array. Then you want to get the first element.

Sign up to request clarification or add additional context in comments.

3 Comments

The for is not at all required.
Thats what I also tried in for loop, but its giving me error saying incompatible type.
@Winn Well.. don't use it in loop. Just wrote what I suggested.
0

You don't need the for. The get() fetches a single value.

String[] s = subjects.get("Animal");
System.out.println(s[0]);

Comments

0

If you tried to use the following code:

  for(String[] s:subjects.get("Animal"))
     System.out.println(s[0]);

If it is working, then subjects.get("Animal") should be a type of String[][]. BUt in your code, it is a type of String[]. They are not matching..

Use System.out.println(subjects.get("Animal")[0]); to print the first element in array.

Comments

0

Since the value of HashMap is a String array, just give the index of your desired value. Say, you want to see "Lion". Since its index is 0 at Animal array, you can say

System.out.println(subjects.get("Animal")[0]);

Output:

Lion

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.