Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get ArrayList<NameValuePair> value by name

Tags:

java

android

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 ?

like image 694
Raptor Avatar asked Jun 05 '13 12:06

Raptor


2 Answers

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.

like image 62
Jon Skeet Avatar answered Oct 20 '22 01:10

Jon Skeet


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.

like image 20
Djon Avatar answered Oct 20 '22 00:10

Djon