jsan
jsan

Reputation: 1057

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?

Upvotes: 2

Views: 9194

Answers (4)

Piyush Ghediya
Piyush Ghediya

Reputation: 1834

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

 IntStream.rangeClosed('A', 'Z').mapToObj(var -> String.valueOf((char) var)).forEach(System.out::println);

Upvotes: 0

RealSkeptic
RealSkeptic

Reputation: 34618

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);

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

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);
}

Upvotes: 1

Justin Kiang
Justin Kiang

Reputation: 1290

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.

Upvotes: 8

Related Questions