![](/img/trans.png)
[英]How to convert List<NameValuePair> into a List<Map.Entry<String, String>>?
[英]Convert Map<String, String> to List<NameValuePair> - is this the most efficient?
我有一個Map<String, String> pairs
並想將其轉換為具有NameValuePair
對象的ArrayList
。 這是執行轉換的最佳方法嗎?
List<NameValuePair> nvpList = new ArrayList<NameValuePair>(2);
for(Map.Entry<String, String> entry : pairs.entrySet()){
NameValuePair n = new NameValuePair(entry.getKey(), entry.getValue());
nvpList.add(n);
}
如果您絕對必須使用NameValuePair,則可以。 我唯一建議的是創建大小為pair.size()的ArrayList,以避免ArrayList隨着內部數組的逐漸增長而多次調整其大小的開銷:
List<NameValuePair> nvpList = new ArrayList<>(pairs.size());
for (Map.Entry<String, String> entry : pairs.entrySet()) {
nvpList.add(new NameValuePair(entry.getKey(), entry.getValue()));
}
對於未來的讀者:
@Locoboy您的代碼段需要一些更正,並且@LeffeBrune的答案將失敗,因為您無法實例化接口。
需要更正這一行:
nvpList.add(new NameValuePair(entry.getKey(), entry.getValue()));
像這樣:
nvpList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
BasicNameValuePair類實現NameValuePair接口,因此可以在此處使用。
請參閱下面的完整正確代碼段:
public List<NameValuePair> convertToNameValuePair(Map<String, String> pairs) {
List<NameValuePair> nvpList = new ArrayList<>(pairs.size());
for (Map.Entry<String, String> entry : pairs.entrySet()) {
nvpList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
return nvpList;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.