83

Right now I'm doing

for (char c = 'a'; c <= 'z'; c++) {
    alphabet[c - 'a'] = c;
}

but is there a better way to do it? Similar to Scala's 'a' to 'z'

MC Emperor
  • 20,870
  • 14
  • 76
  • 119
Stupid.Fat.Cat
  • 9,713
  • 18
  • 73
  • 133

16 Answers16

215

I think that this ends up a little cleaner, you don't have to deal with the subtraction and indexing:

char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
Hunter McMillen
  • 56,682
  • 21
  • 115
  • 164
  • 5
    And you can easily add additional characters as desired. – Hot Licks Jul 10 '13 at 16:29
  • 2
    Ah, figured there might've been a cleaner way to do it without typing everything out or loops. :( I suppose I'll go with this one. Thanks! – Stupid.Fat.Cat Jul 10 '13 at 17:01
  • @HunterMcMillen Java source files _are_ Unicode (so, in a string literal, that's what you have and that's all you can add). – Tom Blodget Jan 02 '15 at 15:23
  • Swift 2: let alphabet = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZ".characters) – Viktor Kucera Mar 03 '16 at 14:37
  • Would be nice of that string constant was available somewhere (commons or spring or jdk) already. – Thilo Apr 28 '16 at 04:29
  • 1
    @Thilo possibly, but not all users are likely to use the *same* alphabet, so then you are in the tricky situation of "Do we store all alphabets as constants?" or "Can we even do that reasonably since some alphabets are very large?" – Hunter McMillen Apr 28 '16 at 12:57
  • How do you ensure that no latter is omitted? E.g. when reading/reviewing code like this? – Piotr Findeisen Sep 27 '17 at 12:40
51
char[] alphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
stinepike
  • 52,673
  • 14
  • 90
  • 109
21

This getAlphabet method uses a similar technique as the one described this the question to generate alphabets for arbitrary languages.

Define any languages an enum, and call getAlphabet.

char[] armenianAlphabet = getAlphabet(LocaleLanguage.ARMENIAN);
char[] russianAlphabet = getAlphabet(LocaleLanguage.RUSSIAN);

// get uppercase alphabet 
char[] currentAlphabet = getAlphabet(true);
    
System.out.println(armenianAlphabet);
System.out.println(russianAlphabet);
System.out.println(currentAlphabet);

Result

I/System.out: աբգդեզէըթժիլխծկհձղճմյնշոչպջռսվտրցւփքօֆ

I/System.out: абвгдежзийклмнопрстуфхцчшщъыьэюя

I/System.out: ABCDEFGHIJKLMNOPQRSTUVWXYZ

private char[] getAlphabet() {
    return getAlphabet(false);
}

private char[] getAlphabet(boolean flagToUpperCase) {
    Locale locale = getResources().getConfiguration().locale;
    LocaleLanguage language = LocaleLanguage.getLocalLanguage(locale);
    return getAlphabet(language, flagToUpperCase);
}

private char[] getAlphabet(LocaleLanguage localeLanguage, boolean flagToUpperCase) {
    if (localeLanguage == null)
        localeLanguage = LocaleLanguage.ENGLISH;

    char firstLetter = localeLanguage.getFirstLetter();
    char lastLetter = localeLanguage.getLastLetter();
    int alphabetSize = lastLetter - firstLetter + 1;

    char[] alphabet = new char[alphabetSize];

    for (int index = 0; index < alphabetSize; index++) {
        alphabet[index] = (char) (index + firstLetter);
    }

    if (flagToUpperCase) {
        alphabet = new String(alphabet).toUpperCase().toCharArray();
    }

    return alphabet;
}

private enum LocaleLanguage {
    ARMENIAN(new Locale("hy"), 'ա', 'ֆ'),
    RUSSIAN(new Locale("ru"), 'а','я'),
    ENGLISH(new Locale("en"), 'a','z');

    private final Locale mLocale;
    private final char mFirstLetter;
    private final char mLastLetter;

    LocaleLanguage(Locale locale, char firstLetter, char lastLetter) {
        this.mLocale = locale;
        this.mFirstLetter = firstLetter;
        this.mLastLetter = lastLetter;
    }

    public Locale getLocale() {
        return mLocale;
    }

    public char getFirstLetter() {
        return mFirstLetter;
    }

    public char getLastLetter() {
        return mLastLetter;
    }

    public String getDisplayLanguage() {
        return getLocale().getDisplayLanguage();
    }

    public String getDisplayLanguage(LocaleLanguage locale) {
        return getLocale().getDisplayLanguage(locale.getLocale());
    }

    @Nullable
    public static LocaleLanguage getLocalLanguage(Locale locale) {
        if (locale == null)
            return LocaleLanguage.ENGLISH;

        for (LocaleLanguage localeLanguage : LocaleLanguage.values()) {
            if (localeLanguage.getLocale().getLanguage().equals(locale.getLanguage()))
                return localeLanguage;
        }

        return null;
    }
}
Lii
  • 10,777
  • 7
  • 58
  • 79
Vahe Gharibyan
  • 4,207
  • 2
  • 29
  • 39
18

This is a fun Unicode solution:

char[] alpha = new char[26]
for(int i = 0; i < 26; i++){
    alpha[i] = (char)(97 + i)
}

This generates a lower-cased version of alphabet, if you want upper-cased, you can replace '97' with '65'.

Tomerikoo
  • 15,737
  • 15
  • 35
  • 52
Boris
  • 785
  • 1
  • 7
  • 20
15

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

IntStream.rangeClosed('A', 'Z').mapToObj(var -> (char) var).forEach(System.out::println);
Piyush Ghediya
  • 1,584
  • 1
  • 13
  • 16
9

If you are using Java 8

char[] charArray = IntStream.rangeClosed('A', 'Z')
    .mapToObj(c -> "" + (char) c).collect(Collectors.joining()).toCharArray();
tom thomas
  • 91
  • 1
  • 1
  • 1
    Hm yes - it seems there is no good solution for this using streams, as there is no CharStream. If you add a bit of explanation I might even upvote, although I wouldn't recommend this approach - it is in no way better than the loops. – Hulk Jul 26 '16 at 10:20
  • 1
    @Hulk: sure but you could return a `Stream CharStream = IntStream.rangeClosed('a', 'z').mapToObj(c -> (char) c);` and use that from that point on. http://stackoverflow.com/questions/22435833/why-is-string-chars-a-stream-of-ints-in-java-8 – Klemen Tusar Apr 18 '17 at 21:28
  • @techouse sure, but the OP wanted a `char[]` - for that, the boxing and unboxing cannot be avoided with streams. – Hulk Apr 19 '17 at 09:00
6
static String[] AlphabetWithDigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
Joost
  • 15
  • 2
4

Check this once I'm sure you will get a to z alphabets:

for (char c = 'a'; c <= 'z'; c++) {
    al.add(c);
}
System.out.println(al);'
Remi Guan
  • 20,142
  • 17
  • 60
  • 81
4

with io.vavr

public static char[] alphanumericAlphabet() {
    return CharSeq
            .rangeClosed('0','9')
            .appendAll(CharSeq.rangeClosed('a','z'))
            .appendAll(CharSeq.rangeClosed('A','Z'))
            .toCharArray();
}
jker
  • 455
  • 3
  • 12
3

Here are a few alternatives based on @tom thomas' answer.

Character Array:

char[] list = IntStream.concat(
                IntStream.rangeClosed('0', '9'),
                IntStream.rangeClosed('A', 'Z')
        ).mapToObj(c -> (char) c+"").collect(Collectors.joining()).toCharArray();

String Array:

Note: Won't work correctly if your delimiter is one of the values, too.

String[] list = IntStream.concat(
                IntStream.rangeClosed('0', '9'),
                IntStream.rangeClosed('A', 'Z')
        ).mapToObj(c -> (char) c+",").collect(Collectors.joining()).split(",");

String List:

Note: Won't work correctly if your delimiter is one of the values, too.

List<String> list = Arrays.asList(IntStream.concat(
                IntStream.rangeClosed('0', '9'),
                IntStream.rangeClosed('A', 'Z')
        ).mapToObj(c -> (char) c+",").collect(Collectors.joining()).split(","));
Tomerikoo
  • 15,737
  • 15
  • 35
  • 52
ScrappyDev
  • 1,815
  • 8
  • 34
  • 53
1

For Android developers searching for a Kotlin solution and ending up here:

// Creates List<Char>
val chars1 = ('a'..'z').toList()
// Creates Array<Char> (boxed)
val chars2 = ('a'..'z').toList().toTypedArray()
// Creates CharArray (unboxed)
val chars3 = CharArray(26) { 'a' + it }
// Creates CharArray (unboxed)
val chars4 = ('a'..'z').toArray()
fun CharRange.toArray() = CharArray(count()) { 'a' + it }

To see what I mean by "boxed" and "unboxed" see this post.
Many thanks to this Kotlin discussion thread.

Mahozad
  • 11,316
  • 11
  • 73
  • 98
0
char[] abc = new char[26];

for(int i = 0; i<26;i++) {
    abc[i] = (char)('a'+i);
}
Sergi
  • 3
  • 2
0

Using Java 8 streams

  char [] alphabets = Stream.iterate('a' , x -> (char)(x + 1))
            .limit(26)
            .map(c -> c.toString())
            .reduce("", (u , v) -> u + v).toCharArray();
Nishant
  • 1,125
  • 1
  • 9
  • 27
0

To get uppercase letters in addition to lower case letters, you could also do the following:

String alphabetWithUpper = "abcdefghijklmnopqrstuvwxyz" + "abcdefghijklmnopqrstuvwxyz".toUpperCase();
char[] letters = alphabetWithUpper.toCharArray();
applecrusher
  • 5,198
  • 3
  • 38
  • 83
-1
import java.util.*;
public class Experiments{


List uptoChar(int i){
       char c='a'; 
        List list = new LinkedList();
         for(;;) {
           list.add(c);
       if(list.size()==i){
             break;
           }
       c++;
            }
        return list;
      } 

    public static void main (String [] args) {

        Experiments experiments = new Experiments();
          System.out.println(experiments.uptoChar(26));
    } 
  • 1
    Is this an intentional attempt at obfuscation? `for(;;)` with an external counter and `break`... and no check that `i>='a'` – Hulk Jul 26 '16 at 10:26
-6
for (char letter = 'a'; letter <= 'z'; letter++)
{
    System.out.println(letter);
}
ChrisF
  • 131,190
  • 30
  • 250
  • 321
jaimebl
  • 59
  • 2