4

I'm capturing parameters from a request url using com.apache.http.NameValuePairwhich basically store those params in List<NameValuePair>. To do certain checks and verifications on those params, I need to convert that list into a HashMap<String, String>. Is there a way to do this conversion?

Donshon
  • 174
  • 2
  • 11
  • 2
    Assuming you want to make the "name" the key in the hashmap, just iterate over the list and add to the map. However, doing this blindly can lead to problems if the list contains a duplicate "name". The map would end up containing only the "last" value for the duplicate key. You need to better specify what you are trying to accomplish if you want a meaningful answer. This smells like an [XY Problem](http://xyproblem.info) – Jim Garrison Mar 11 '16 at 19:01
  • what should the key and value be? – Rishi Mar 11 '16 at 19:01
  • @JimGarrison You're right, I'm trying to make the "name" as the key. As for duplicated names, chances of that happening is almost 0. So if I iterate through the list and add it to the map, how do I specify to have 'name' as the key and 'value' (from list) as value in the map? – Donshon Mar 11 '16 at 19:06

2 Answers2

13

Do you use Java 8? In that case you could make use of the Collectors.toMap() method:

Map<String, String> mapped = list.stream().collect(
        Collectors.toMap(NameValuePair::getName, NameValuePair::getValue));

Otherwise you would have to loop through the elements

for(NameValuePair element : list) {
  //logic to convert list entries to hash map entries
}

To get a better understanding, please take a look at this tutorial.

Jernej K
  • 1,602
  • 2
  • 25
  • 38
  • There is Missing closing brackets, can't add it back since it is less than 6 characters, can you help add it back in, thanks! `...NameValuePair::getValue));` – Ng Sek Long Sep 27 '18 at 08:33
1

You can use it for Java 8

public static <K, V, T extends V> Map<K, V> toMapBy(List<T> list,
        Function<? super T, ? extends K> mapper) {
    return list.stream().collect(Collectors.toMap(mapper, Function.identity()));
}

And here's how you would use it on a List:

Map<Long, Product> productsById = toMapBy(products, Product::getId);

Follow the link:

  1. Converting ArrayList to HashMap
  2. Generic static method constrains types too much
  3. Java: How to convert List to Map
Community
  • 1
  • 1
SkyWalker
  • 28,384
  • 14
  • 74
  • 132