Get the value of ArrayList <NameValuePair> by name

Is this the correct way to get the value of an ArrayList<NameValuePair> 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 the ArrayList<NameValuePair> value by name?

+8
java android
source share
4 answers

No - you save them as a list that is not intended to access the "key" - it does not have the concept of a key.

It sounds like you really need something like Map<String, String> - provided that you only need to store one value for each key.

If you are stuck with an ArrayList (and I would at least change the type of the parameter to List , if not Iterable , considering that everything you need), then you are fine.

+9
source share

If you can use Map instead, they will work as follows:

 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"); 

When using HashMap keys are not saved as a list, so it will be faster and you will not have to use the function to iterate the container.

Then you can access all the values โ€‹โ€‹using myMap.keySet() and myMap.values() , see the documentation.

+5
source share

You seem to need a different 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 the pairs are stored in a list. The map allows you to get a set of values; Collection is a super List interface.

+4
source share

if your key or name is an integer, I suggest using SparseArray : http://developer.android.com/reference/android/util/SparseArray.html

Then you can use different functions to retrieve the values โ€‹โ€‹you want using the key, value or index in the array.

+1
source share

All Articles