【问题标题】:How to convert List<NameValuePair> into a hashMap<String, String>?如何将 List<NameValuePair> 转换为 hashMap<String, String>?
【发布时间】:2016-06-27 03:34:44
【问题描述】:

我正在使用 com.apache.http.NameValuePair 从请求 url 中捕获参数,它基本上将这些参数存储在 List&lt;NameValuePair&gt; 中。要对这些参数进行某些检查和验证,我需要将该列表转换为 HashMap&lt;String, String&gt;。有没有办法进行这种转换?

【问题讨论】:

  • 假设您想让“名称”成为哈希图中的键,只需遍历列表并添加到地图中。但是,如果列表包含重复的“名称”,那么盲目地这样做可能会导致问题。该映射最终将仅包含重复键的“最后一个”值。如果您想要一个有意义的答案,您需要更好地指定您要完成的工作。这闻起来像 XY Problem
  • key和value应该是什么?
  • @JimGarrison 你说得对,我正在尝试将“名称”作为关键。至于重复的名称,发生这种情况的可能性几乎为 0。因此,如果我遍历列表并将其添加到地图中,我如何指定将“名称”作为键,将“值”(来自列表)作为值地图?

标签: java arraylist hashmap


【解决方案1】:

您使用 Java 8 吗?在这种情况下,您可以使用 Collectors.toMap() 方法:

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

否则你将不得不遍历元素

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

为了更好地理解,请看一下这个tutorial

【讨论】:

  • 缺少右括号,由于少于6个字符,无法重新添加,请您帮忙重新添加,谢谢! ...NameValuePair::getValue));
【解决方案2】:

您可以将它用于 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()));
}

下面是你如何在列表中使用它:

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

点击链接:

  1. Converting ArrayList to HashMap
  2. Generic static method constrains types too much
  3. Java: How to convert List to Map

【讨论】:

  • Function.identity() 非常好,尤其是当您不输入 Functions.identity()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-30
  • 2015-09-28
  • 1970-01-01
  • 2018-07-16
  • 2018-11-26
  • 1970-01-01
相关资源
最近更新 更多