-2

I need iterate through hashmap and get key value which should be a string and all values within that key which is a list of strings that have strings?

Psuedo code

static HashMap<String, List<String>> vertices  = new HashMap<String, List<String>>();
for (int i = 0; i < vertices.size(); i++)
{

       String key = vertices.getKey at first postions;

    for (int x = 0; x < size of sublist of the particular key; x++)
       {
              String value = vertices key sublist.get value of sublist at (i);

          }
}
MAXGEN
  • 735
  • 1
  • 10
  • 21
  • 1
    possible duplicate of [Java: iterate through HashMap](http://stackoverflow.com/questions/1066589/java-iterate-through-hashmap) – Bucket Mar 28 '14 at 19:27
  • What about particular situation of it being a list? How do I get the list of that particular key? I also need the string value of that key as well as the values of the list? – MAXGEN Mar 28 '14 at 19:29
  • Should I delete this post? – MAXGEN Mar 28 '14 at 21:04
  • Can I delete this post, moderator? Thanks. – MAXGEN Apr 01 '14 at 01:26

2 Answers2

1

Try vertices.keySet();

It gives a Set of all keys in the map. Use it in a for loop like below

for (String key : vertices.keySet()) {
   for (String value : vertices.get(key)) { 
       //do stuff
   }
}
Mason T.
  • 1,567
  • 1
  • 14
  • 33
  • How do iterate the list and String value would be list object instead of string? – MAXGEN Mar 28 '14 at 19:33
  • @MAXGEN In this, `vertices.get(key)` is the list, and each `String value` is an element of the `List` value for `key`. The second loop _is_ iterating over the list. – Michelle Mar 28 '14 at 19:38
1

You can't iterate over HashMap directly, as there is no numeric index of values within HashMap. Instead key values are used, in your case of type String. Therefore the values don't have a particular order. However, if you want, you can construct a set of entries and iterate over that, using vertices.entrySet().

for (Entry<String, List<String>> item : vertices.entrySet()) {
    System.out.println("Vertex: " + item);
    for (String subitem : item.getValue()) {
        System.out.println(subitem);
    }
}
Warlord
  • 2,798
  • 16
  • 21