简体   繁体   English

如何转换List <NameValuePair> 进入hashMap <String, String> ?

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

I'm capturing parameters from a request url using com.apache.http.NameValuePair which basically store those params in List<NameValuePair> . 我正在使用com.apache.http.NameValuePair从请求URL捕获参数,它基本上将这些参数存储在List<NameValuePair> To do certain checks and verifications on those params, I need to convert that list into a HashMap<String, String> . 要对这些参数进行某些检查和验证,我需要将该列表转换为HashMap<String, String> Is there a way to do this conversion? 有没有办法进行这种转换?

Do you use Java 8? 你使用Java 8吗? In that case you could make use of the Collectors.toMap() method: 在这种情况下,您可以使用Collectors.toMap()方法:

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 . 为了更好地理解,请查看本教程

You can use it for Java 8 您可以将它用于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: 以下是如何在List上使用它:

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

Follow the link: 点击链接:

  1. Converting ArrayList to HashMap 将ArrayList转换为HashMap
  2. Generic static method constrains types too much 通用静态方法过多地约束类型
  3. Java: How to convert List to Map Java:如何将List转换为Map

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM