88

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'

Vahe Gharibyan
  • 5,277
  • 4
  • 36
  • 47
Stupid.Fat.Cat
  • 10,755
  • 23
  • 83
  • 144

17 Answers17

227

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
  • 59,865
  • 24
  • 119
  • 170
  • 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
58
char[] LowerCaseAlphabet = {'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'};

char[] UpperCaseAlphabet = {'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'};
Gaël J
  • 11,274
  • 4
  • 17
  • 32
stinepike
  • 54,068
  • 14
  • 92
  • 112
26

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
  • 11,553
  • 8
  • 64
  • 88
Vahe Gharibyan
  • 5,277
  • 4
  • 36
  • 47
18

This is a fun Unicode solution:

int charAmount = 'z' - 'a' + 1;

char[] alpha = new char[charAmount];
for(int i = 0; i < charAmount ; i++){
    alpha[i] = (char)('a' + i);
}

System.out.println(alpha); //abcdefghijklmnopqrstuvwxyz

This generates a lower-cased version of alphabet.
If you want upper-cased, you can replace 'a' with 'A' at ('a' + i).

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Boris
  • 805
  • 1
  • 8
  • 20
17

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,754
  • 1
  • 14
  • 17
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
  • 21,506
  • 17
  • 64
  • 87
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
  • 465
  • 3
  • 13
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
  • 18,379
  • 16
  • 47
  • 61
ScrappyDev
  • 2,307
  • 8
  • 40
  • 60
3

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
  • 18,032
  • 13
  • 118
  • 133
1
char[] abc = new char[26];

for(int i = 0; i<26;i++) {
    abc[i] = (char)('a'+i);
}
Sergi
  • 13
  • 3
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,142
  • 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,508
  • 5
  • 39
  • 89
0
var alphabet = IntStream.rangeClosed('a', 'z')
    .boxed()
    .map(Character::toChars)
    .map(String::valueOf)
    .toList();

Notes

  • rangeClosed() in order to make it 'z' inclusive
  • boxed() in order to create a list from an IntStream
  • toList() creates an unmodifiable list, but is apparently only available starting with Java 16
orustammanapov
  • 1,792
  • 5
  • 25
  • 44
-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
  • 134,786
  • 31
  • 255
  • 325
jaimebl
  • 59
  • 2