Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Get value from HashMap

I have tried to search on HashMap in Android, but getting problem:

Consider this example:

HashMap<String, String> meMap=new HashMap<String, String>(); meMap.put("Color1","Red"); meMap.put("Color2","Blue"); meMap.put("Color3","Green"); meMap.put("Color4","White"); 

now I want to iterate it and get the value of each color and want to display in "Toast". how do I display it?

like image 802
Paresh Mayani Avatar asked Aug 06 '10 09:08

Paresh Mayani


People also ask

How do I find the value of a key on a map?

HashMap get() Method in Java util. HashMap. get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.

How does the HashMap class store the data in Android?

It stores the data in the pair of Key and Value. HashMap contains an array of the nodes, and the node is represented as a class. It uses an array and LinkedList data structure internally for storing Key and Value. There are four fields in HashMap.


2 Answers

Iterator myVeryOwnIterator = meMap.keySet().iterator(); while(myVeryOwnIterator.hasNext()) {     String key=(String)myVeryOwnIterator.next();     String value=(String)meMap.get(key);     Toast.makeText(ctx, "Key: "+key+" Value: "+value, Toast.LENGTH_LONG).show(); } 
like image 148
Pentium10 Avatar answered Oct 16 '22 06:10

Pentium10


Here's a simple example to demonstrate Map usage:

Map<String, String> map = new HashMap<String, String>(); map.put("Color1","Red"); map.put("Color2","Blue"); map.put("Color3","Green"); map.put("Color4","White");  System.out.println(map); // {Color4=White, Color3=Green, Color1=Red, Color2=Blue}          System.out.println(map.get("Color2")); // Blue  System.out.println(map.keySet()); // [Color4, Color3, Color1, Color2]  for (Map.Entry<String,String> entry : map.entrySet()) {     System.out.printf("%s -> %s%n", entry.getKey(), entry.getValue()); } // Color4 -> White // Color3 -> Green // Color1 -> Red // Color2 -> Blue 

Note that the entries are iterated in arbitrary order. If you need a specific order, then you may consider e.g. LinkedHashMap

See also

  • Effective Java 2nd Edition, Item 52: Refer to objects by their interfaces
  • Java Tutorials/Collections - The Map interface
  • Java Language Guide/The for-each loop

Related questions

On iterating over entries:

  • Iterate Over Map
  • iterating over and removing from a map
    • If you want to modify the map while iterating, you'd need to use its Iterator.

On different Map characteristics:

  • How to Maintain order of insertion using collections

On enum

You may want to consider using an enum and EnumMap instead of Map<String,String>.

See also

  • Java Language Guide/Enums

Related questions

  • Enumerations: Why? When?
like image 26
polygenelubricants Avatar answered Oct 16 '22 08:10

polygenelubricants