1

Is there any method to convert the map obtained from servletRequest.getParameterMap() which returns a Map<String, String[]> to Map<String, Object[]> in a simple way other than a for loop?

I have a method getSomething() which is declared as

public Response getSomething(final Map<String, Object[]) 

I have to call this method with servletRequest.getParameterMap() as input.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • 4
    Your question looks like [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Can you add more info about why you need this change? – Pshemo Jul 16 '15 at 19:42
  • 1
    Also what do you mean by *convert*? Can we assume that you want to get new independent map which will be copy of original one (since otherwise you could try adding `Integers` to array of Objects which really will be still array for Strings). – Pshemo Jul 16 '15 at 19:56
  • 1
    Just in case you don't know it: to add more informations to your question use [edit] option. – Pshemo Jul 16 '15 at 19:59

2 Answers2

7

Sure.

Map<String, Object[]> objectMap = 
    Collections.unmodifiableMap(servletRequest.getParameterMap());

This is correct, type-safe, and doesn't risk problems with accidentally putting wrongly typed values into the map.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • 2
    I also doesn't prevent us from trying to place non-string value to `String[]` array via `Object[]` reference (although this behaviour will be stopped at runtime). – Pshemo Jul 16 '15 at 20:09
0

This way uses Java raw types.

Map<String, String[]> map1 = new HashMap<>();
Map<String, Object[]> map2 = (Map)map1;

This is a working solution although, as Pshemo pointed out, java raw types shouldn't be used.

Community
  • 1
  • 1
Kamil Jarosz
  • 2,168
  • 2
  • 19
  • 30
  • 4
    Mandatory link: [What is a raw type and why shouldn't we use it?](http://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) – Pshemo Jul 16 '15 at 20:11