0

Here is my Java code:

public static void main(String[] args) {  
    Map<String, String> map = new HashMap<String, String>();  
    map.put("_name", "name");  
    map.put("_age", "age");  
    Set<String> set = map.keySet();  
    Iterator iterator = set.iterator();  
    // the first iteration  
    StringBuffer str1 = new StringBuffer();  
    while (iterator.hasNext()) {  
        str1.append(iterator.next() + ",");  
    }  
    String str1To = str1.substring(0, str1.lastIndexOf(",")).toString();  
    System.out.println(str1To);  
    // the second iteration  
    StringBuffer str2 = new StringBuffer();  
    while (iterator.hasNext()) {  
        str2.append(iterator.next() + ",");  
    }  
    String str2To = str2.substring(0, str2.lastIndexOf(",")).toString();// ?????  
    System.out.println(str2To);  
}

My question is,why doesn't the second loop iterate? Does the first iteration already takes the iterator to the end? Is this what affects the second iteration?

How do I fix it?

3 Answers 3

3

Your first while loop would move iterate till the iterator reaches the end of the list. At that moment the iterator in itself is pointing to the end of the list, in your case the map.keySet(). And that is the reason why your next while loop fails because the call to the iterator.hasNext() returns false.

A better way would be to use the Enhanced For Loop, something like this instead of your while loops:

for(String key: map.keySet()){
    //your logic
}
Sign up to request clarification or add additional context in comments.

Comments

0

Iterator's are for one time use only. So ask for iterator again.

Comments

0

You need to call set.iterator() each time you want to iterate through a collection. I suggest that you use a different variable for each iteration as well.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.