[英]Convert Map<String, String> to List<NameValuePair> - is this the most efficient?
I have a Map<String, String> pairs
and want to turn this into an ArrayList
with NameValuePair
objects. 我有一个
Map<String, String> pairs
并想将其转换为具有NameValuePair
对象的ArrayList
。 Is this the best way to execute the conversion? 这是执行转换的最佳方法吗?
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);
}
If you absolutely have to use NameValuePair, than yes. 如果您绝对必须使用NameValuePair,则可以。 Only thing I would suggest is creating ArrayList of a size of pairs.size() to avoid overhead of ArrayList resizing internal array multiple times as it grows gradually:
我唯一建议的是创建大小为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()));
}
For future readers: 对于未来的读者:
@Locoboy your code snippet needs some correction and @LeffeBrune's answer will fail since you cannot instantiate an interface. @Locoboy您的代码段需要一些更正,并且@LeffeBrune的答案将失败,因为您无法实例化接口。
Need to correct this line: 需要更正这一行:
nvpList.add(new NameValuePair(entry.getKey(), entry.getValue()));
like so: 像这样:
nvpList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
The BasicNameValuePair class implements the NameValuePair interface so it can be used here. BasicNameValuePair类实现NameValuePair接口,因此可以在此处使用。
See full correct code snippet below: 请参阅下面的完整正确代码段:
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.