-5

I am modifying someone else code. I have a variable of type List<HashMap<String, String>>

List<HashMap<String, String>> lst

I tried to use get the item single value by using

lst[0,1]
lst[0][1]
lst.get(0)[1]
lst.get(0)(1)
lst.get(0)("ID")

but non works.

how to get a single item value?

    List<HashMap<String, String>> lst = null;

    try{
        lst = myXmlParser.detparse(reader);
    }catch(Exception e){
        Log.d("Exception", e.toString());
    }
5
  • use list.get(index); it will return you an object of type HashMap<String,String> index here is an int of your choice. Commented Jul 7, 2014 at 9:43
  • Should be List<Map<String, String>> lst Commented Jul 7, 2014 at 9:46
  • I used list.get(index) but it will not return a single value it will return a list of 4 items Commented Jul 7, 2014 at 9:46
  • possible duplicate of Java: get specific ArrayList item Commented Jul 7, 2014 at 9:48
  • Not sure what the code producing the List<HashMap<String,String>> by getparse is meant to say in connection with the question "how to get a single item". Commented Jul 7, 2014 at 9:57

4 Answers 4

1

You should read the documentation of List and Map (respective HashMap) to see how to use them.

Since your List contains Map you'll have to get a Map using the List operations and then get the elements from that Map using the Map operations:

HashMap<String, String> firstMap = lst.get(0);
String someEntry = firstMap.get("key");
Sign up to request clarification or add additional context in comments.

Comments

0
HashMap<String, String> firstEntryInList = list.get(0);

Where '0' is the index.

Comments

0

Why not using index of list...

HashMap<String, String> entry = lst.get(0);

2 Comments

@DownVoter, Can it be commented, why to down vote? To return an element from a list using indexes - use get(index) is the suggestion and its appropriate to the question.
I think that a rather weird one was downvoting each and every answer on this Q. I got credited +8, which looks like one up and one down, others may have experienced similar.
0

Accessor methods must be applied from outer to inner. If you have a

List<Whatever> lst

you use

lst.get(0)

to retrieve the first element in the list. If Whatever is in turn an aggregate, you apply the appropriate accessor on the returned value:

List<Map<String,String>> lst

and to get the string that's mapped via "somekey":

lst.get(0).get("somekey")

Now, this will get you a String, and this has accessors, too, eg. for accessing a single character:

lst.get(0).get("somekey").charAt(0)

This is "the first character of the string mapped with key "somekey" in the first hash map of the list lst".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.