Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Map<String, String> to List<NameValuePair> - is this the most efficient?

Tags:

java

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);
}
like image 241
locoboy Avatar asked Nov 30 '25 06:11

locoboy


1 Answers

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()));
}
like image 178
LeffeBrune Avatar answered Dec 01 '25 20:12

LeffeBrune