Get 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.
It seems that you need other data structure. For example Map<Name, Value>
or Map<Name, NameValuePair>
if you want.
The first solution is probably more correct, the second is easier to implement if you already have code that uses the fact that pairs are stored in list. Map allows to get collection of values; Collection
is a super interface of List
.