繁体   English   中英

转换地图 <String, String> 列出 <NameValuePair> -这是最有效的吗?

[英]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.

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