Is it a correct way to get ArrayList<NameValuePair>
value by name ?
private String getValueByKey(ArrayList<NameValuePair> _list, String key) {
for(NameValuePair nvPair : _list) {
if(nvPair.getName().equals(key)) {
return nvPair.getValue().toString();
}
}
return null;
}
Or, is there a shortcut to access ArrayList<NameValuePair>
value by name ?
No - you're storing them as a list, which isn't designed to be accessed by "key" - it doesn't have any notion of a key.
It sounds like really you want something like a Map<String, String>
- assuming you only need to store a single value for each key.
If you're stuck with the ArrayList
(and I'd at least change the parameter type to List
, if not Iterable
given that that's all you need) then what you've got is fine.
If you can use a Map
instead, they work like this:
Map<String,String> myMap = new HashMap<>();
myMap.put("key1","value1");
myMap.put("key2","value2");
myMap.put("key3","value3");
String str = myMap.get("key1");
//equivalent to your
String str = getValueByKey(myList,"key1");
With a HashMap
the keys are not stored as a list, so this will be faster and you won't have to use a function to iterate the container.
You can then access all the values with myMap.keySet()
and myMap.values()
, see the documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With