I have a Map<String, String> pairs
and want to turn this into an ArrayList
with NameValuePair
objects. 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. 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:
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.
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.
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.