'Better way to generate array of all letters in the alphabet

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'



Solution 1:[1]

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

Solution 2:[2]

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

Solution 3:[3]

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'.

Solution 4:[4]

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

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

Solution 5:[5]

If you are using Java 8

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

Solution 6:[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"};

Solution 7:[7]

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

Solution 8:[8]

with io.vavr

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

Solution 9:[9]

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(","));

Solution 10:[10]

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.

Solution 11:[11]

char[] abc = new char[26];

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

Solution 12:[12]

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

Solution 13:[13]

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

Solution 14:[14]

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