Add alphabets to List Java

Alex :

I want create a list with alphabets with each alphabets for 5 times. I tried a code and it worked,

public class AlphabetsTest {
    public static void main(String[] args) {
        List<Character> alphabetList = new ArrayList<>();
        for (int i=0; i<3; i++){
            char chr='a';
            if (i==1)
                chr = 'b';
            if (i==2)
                chr = 'c';
            for (int j=0; j<5; j++){
                alphabetList.add(chr);
            }
        }
    }
}

But I would have to add multiple if conditions for more alphabets. Is there any better way to avoid it.

Code_Mode :

You can use char loop as below,

List<Character> alphabetList = new ArrayList<>();
    for(char chr = 'a'; chr <= 'c'; chr++){
        for (int j=0; j<5; j++){
            alphabetList.add(chr);
    }
}

You may also want to use, Collections.nCopies to avoid inner loop,

for(char chr = 'a'; chr <= 'c'; chr++){
    alphabetList.addAll(Collections.nCopies(5, chr));
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=403409&siteId=1