15

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));
    } 
John Doe
  • 2,752
  • 5
  • 40
  • 58
  • 1
    Map is not ordered. Please note :) Get ready for surprises. – Suresh Atta Jul 28 '14 at 08:28
  • But the List is. The values of the keys in the Map are List of String. I may be wrong feel free to correct me. – John Doe Jul 28 '14 at 08:29
  • But each time you'll get a different List as you don't know which is at place one. Making sense ? – Suresh Atta Jul 28 '14 at 08:30
  • What I want is that this method should return a map of key and its corresponding first value. I know there is a method getFirst() in MultivaluedMap. How to use it here? – John Doe Jul 28 '14 at 08:36

2 Answers2

24

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;

    }
John Doe
  • 2,752
  • 5
  • 40
  • 58
  • 8
    One could simply use `for(String theKey : queryParameters.keySet()) { ... }` instead of working directly with `Iterator`. – Dinei Jun 23 '17 at 19:49
2

Or using streams...

queryParameters.getRequestHeaders().entrySet().stream()
.collect(
    Collectors.toMap(
        Map.Entry::getKey, entry -> entry.getValue().stream().findFirst().orElse(null)));   
Jainendra
  • 24,713
  • 30
  • 122
  • 169
Gregor
  • 385
  • 3
  • 15