2

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?

jsan
  • 1,047
  • 8
  • 20
  • 33

4 Answers4

8

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.

Justin Kiang
  • 1,270
  • 6
  • 13
1

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);
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

First problem: When you work with a HashMap, you are supposed to map a key to a value. You don't just put something in a hash map. The letter you wanted to put, is it a value? Then what is the key? Is it a key? Then what is the value?

You might think that using "null" as a value is a good idea, but you should ask yourself: in that case, should I use a map at all? Maybe using a HashSet is a better idea?

The second problem is that a HashMap, like all java collections, only takes objects - both as keys and as values. If you want to use a character as a key, you could define your map as Map<Character,Map<String,Student>>, which will auto-box your character (convert it to an object of type Character) or you could convert the character to a string using

Character.toString(alphabet);
RealSkeptic
  • 33,993
  • 7
  • 53
  • 79
0

In Java 8 with Stream API, you can do this.

 IntStream.rangeClosed('A', 'Z').mapToObj(var -> String.valueOf((char) var)).forEach(System.out::println);
Piyush Ghediya
  • 1,754
  • 1
  • 14
  • 17