I want to loop through the alphabet with a for loop and add each letter to my HashMap
for(char alphabet = 'A'; alphabet <= 'Z';alphabet++) {
System.out.println(alphabet);
}
doesn't work for me, because my HashMap is of form
HashMap<String, HashMap<String, Student>> hm;
I need my iterator to be a string, but
for(String alphabet = 'A'; alphabet <= 'Z';alphabet++) {
System.out.println(alphabet);
}
doesn't work.
Basically, I want to do this:
for i from 'A' to 'Z' do
hm.put(i, null);
od
Any ideas?
Basically convert the char to a string, like this:
for(char alphabet = 'A'; alphabet <= 'Z';alphabet++) {
hm.put(""+alphabet, null);
}
Although ""+alphabet is not efficient as it boils down to a call to StringBuilder
The equivalent but more effective way can be
String.valueOf(alphabet)
or
Character.toString(alphabet)
which are actually the same.
You cannot assign a char to a String, or to increment a string with ++. You can iterate on the char the way you did in your first sample, and convert that char to a String, like this:
for(char letter = 'A'; letter <= 'Z'; letter++) {
String s = new String(new char[] {letter});
System.out.println(s);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With