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?
Your first
whileloop would move iterate till theiteratorreaches the end of the list. At that moment theiteratorin itself is pointing to the end of thelist, in your case themap.keySet(). And that is the reason why your nextwhileloop fails because the call to theiterator.hasNext()returnsfalse.A better way would be to use the
Enhanced For Loop, something like this instead of yourwhileloops: