How to convert List<NameValuePair> into a hashMap<String, String>?

本小妞迷上赌 提交于 2021-01-27 07:07:26

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/35947858/how-to-convert-listnamevaluepair-into-a-hashmapstring-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!