![](/img/trans.png)
[英]Difference between HashMap<String,String> and List<NameValuePair>
[英]How to convert List<NameValuePair> into a hashMap<String, String>?
我正在使用com.apache.http.NameValuePair
從請求URL捕獲參數,它基本上將這些參數存儲在List<NameValuePair>
。 要對這些參數進行某些檢查和驗證,我需要將該列表轉換為HashMap<String, String>
。 有沒有辦法進行這種轉換?
你使用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
}
為了更好地理解,請查看本教程 。
您可以將它用於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()));
}
以下是如何在List上使用它:
Map<Long, Product> productsById = toMapBy(products, Product::getId);
點擊鏈接:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.