Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over MultivaluedMap and extract the key and its corresponding first value?

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));
    } 
like image 526
John Doe Avatar asked Jul 28 '14 08:07

John Doe


2 Answers

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;

    }
like image 69
John Doe Avatar answered Nov 03 '22 11:11

John Doe


Or using streams...

queryParameters.getRequestHeaders().entrySet().stream()
.collect(
    Collectors.toMap(
        Map.Entry::getKey, entry -> entry.getValue().stream().findFirst().orElse(null)));   
like image 45
Gregor Avatar answered Nov 03 '22 12:11

Gregor