Here is my code its my first attempt . But what is the correct way to do this.
private Map<String,String> prepareParameters(MultivaluedMap<String, String> queryParameters) {
Map<String,String> parameters = new HashMap<String,String>();
for (Map.Entry<String,List<String>> e : queryParameters.entrySet()) {
parameters.put(e.getKey(), e.getValue().get(0));
}
One way to do this can be :--
private Map<String,String> prepareParameters(MultivaluedMap<String, String> queryParameters) {
Map<String,String> parameters = new HashMap<String,String>();
Iterator<String> it = queryParameters.keySet().iterator();
while(it.hasNext()){
String theKey = (String)it.next();
parameters.put(theKey,queryParameters.getFirst(theKey));
}
return parameters;
}
OR without using the iterator, as suggested by Dinei Rockenbach, we can do as follow:-
private Map<String,String> prepareParameters(MultivaluedMap<String, String> queryParameters) {
Map<String,String> parameters = new HashMap<String,String>();
for(String str : queryParameters.keySet()){
parameters.put(str, queryParameters.getFirst(str));
}
return parameters;
}
Or using streams...
queryParameters.getRequestHeaders().entrySet().stream()
.collect(
Collectors.toMap(
Map.Entry::getKey, entry -> entry.getValue().stream().findFirst().orElse(null)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With