Add alphabets to List Java [duplicate]

风格不统一 提交于 2020-05-17 06:56:08

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/61027316/add-alphabets-to-list-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!