How to get length of String[] array in a HashMap value

user3473776 Source

I'm making a HashMap to store menu names as a String[] array as a value of the Map. Example:

Map<String, String[]> menu = new HashMap<String, String[]>();

String[] main = {"home", "news", "gallery"};
String[] user = {"profile", "messages"};
String[] admin = {"users", "stats"};
menu.put("main", main);
menu.put("user", user);
menu.put("admin", admin);

The main, user, and admin arrays will hold data from a database but I've put static data in for now to test it. I need to loop through each key's value array by getting the length of the value string. Example:

for(int i=0;i<menu.get("main").length();i++)

The compiler complains about this line of code: menu.get("main").length() - method not found.

If I use a fixed iteration like for(int i=0;i<2;i++) it works fine.

The problem is getting the length of menu.get("main").length() properly!


I'm actually printing the results using JSTL in a JSP page as follows:

<c:set var="main_menu" value="${view.getMenu().get('main')}" />
<c:forEach var="i" begin="0" end="${main_menu.length}">
<c:out value="${main_menu[i]}" />

I'm getting an error from tomcat saying: java.lang.NumberFormatException: For input string: "length"



answered 4 years ago rgettman #1

For arrays, length is accessed as if it were an instance variable, not a method. Change

for(int i=0;i<menu.get("main").length();i++)


for(int i=0;i<menu.get("main").length;i++)

The Java Tutorial on arrays states:

Finally, you can use the built-in length property to determine the size of any array. The following code prints the array's size to standard output:


answered 4 years ago arshajii #2

length is a field, not a method. Also, you shouldn't call get() over and over, store the value somewhere:

String[] value = menu.get("main");

for (int i = 0; i < value.length; i++) {  // notice it's not `length()`

You can also use a for-each:

for (String a : value) {

answered 4 years ago Dawood ibn Kareem #3

Your problem, of course, is the parentheses after length. However, for what you're doing, the best thing would be to use an extended for loop.

for (String item : menu.get("main")) {


To do it in JSTL, you want

<c:forEach var="item" items="${view.getMenu().get('main')}">
    <c:out value="${item}" />

answered 4 years ago Prasad #4

@David has already answered your question, but in case if any scenario you need to iterate with index (iteration number), you can do it as:

    <c:forEach var="item" items="${view.getMenu().get('main')}" varStatus="itemStatus">
        <c:out value="${itemStatus.index}" /> - <c:out value="${item}" />

where "varStatus" loop tag has two fields: index and count. index starts the numbering from 0 and ends at (collection length - 1); count starts the numbering from 1 and ends at (collection length)

The above one will print as:
1 - home
2 - news
3 - gallery

comments powered by Disqus