Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

looping through the alphabet as String

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?

like image 942
jsan Avatar asked Mar 29 '26 21:03

jsan


2 Answers

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.

like image 164
Justin Kiang Avatar answered Apr 01 '26 06:04

Justin Kiang


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);
}
like image 30
Sergey Kalinichenko Avatar answered Apr 01 '26 07:04

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!