Loop through an Enumeration containing Header Names in Java Servlet

Viewed 10047

I want to loop through an enumeration containing all of the header names inside a java servlet. My code is as follows:

public class ServletParameterServlet extends HttpServlet
{
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        ServletConfig c = this.getServletConfig();
        PrintWriter writer = response.getWriter();

        writer.append("database: ").append(c.getInitParameter("database"))
              .append(", server: ").append(c.getInitParameter("server"));

       Enumeration<String> headerNames = ((HttpServletRequest) c).getHeaderNames();


    }
}

Is this the correct syntax? How does one actually iterate over an enums values in Java? And specifically in this instance?

Thanks for your help, Marc

3 Answers

we can use forEachRemaining

    Enumeration<String> headerNames = request.getHeaderNames();
    headerNames.asIterator().forEachRemaining(header -> {
         System.out.println("Header Name:" + header + "   " + "Header Value:" + request.getHeader(header));
    });

You can convert it to List by using the following method:

public static <T> List<T> enumerationToList(final Enumeration<T> enumeration) {
    if (enumeration == null) {
        return new ArrayList<>();
    }
    return Collections.list(enumeration);
}

usage:

final List<String> headerNames = enumerationToList(request.getHeaderNames());

for (final String headerName : headerNames) {
    System.out.println(headerName);
}
Related