What use is Java 6 interface MultivaluedMap?
4 Answers
The interface does not belong to "Java", meaning that the interface is not a part of the core libraries. It is a part of the javax.ws.rs
hierarchy which is part of the JAX-RS specification. It is used by frameworks implementing the specification such as Jersey. It is used whenever maps should refer to not only a single value but to any number of values. An example for the use would be for example the storage of a request header where you one might want to add several values per key. Or even no keys in some cases where it is easier to handle an empty list compared to a null
value.
Take this HTTP-header for example:
Accept-Encoding: compress;q=0.5, gzip;q=1.0
You would model this by
MultivaluedMap<String, String> map = ...
map.add("Accept-Encoding", "compress;q=0.5");
map.add("Accept-Encoding", "gzip;q=1.0");
internally in Jersey. This type of multiple value storage is a common problem in Java that is addressed by other implementors of maps such as Guava.
This is basically what the javadoc says:
A map of key-values pairs. Each key can have zero or more values.

- 42,759
- 13
- 108
- 192
-
1Here is an example on how to initialize it: `MultivaluedMap
map = new MultivaluedMapImpl();` – stefan-dan May 27 '21 at 11:21
Its a map of key-values pairs. Each key can have zero or multiple values
public interface MultivaluedMap<K,V> extends java.util.Map<K,java.util.List<V>>

- 3,290
- 1
- 17
- 18
A good use of a MultivaluedMap is with UriInfo. If you are writing a REST endpoint that takes in several QueryParams, you can use UriInfo to get all of the params and extract them using the getQuery() call. For example:
public void get(@Context UriInfo ui) {
MultivaluedMap params = ui.getRequestUri().getQuery();
// now do what you want with your params
}
The MultivaluedMap is helpful because you could have parameters with multiple values. For example if it was a customer database and you wanted to get several customers, your map would have the key of "customerID" and several values linked to it.

- 816
- 1
- 11
- 20
MultiValuedMap is a part of javax.ws.rs.core
package, not Core Java. It is mainly used for storing Headers values in requests
private MediaType getMediaType(Class entityClass, Type entityType, MultivaluedMap<String, Object> headers) {
final Object mediaTypeHeader = headers.getFirst("Content-Type");
....
}
Also, it is quite useful with UriInfo
private String getJsonpFunctionName(){
UriInfo uriInfo = getUriInfo();
if (uriInfo == null) {
return null;
}
MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
if (queryParameters == null) {
return null;
}
return queryParameters.getFirst("jsonp");
}

- 586
- 5
- 19

- 149
- 1
- 2