将字母添加到列表Java [英] Add alphabets to List Java
本文介绍了将字母添加到列表Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个包含5个字母的列表.我尝试了一个代码,就可以了,
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.
推荐答案
您可以如下使用char
循环
List<Character> alphabetList = new ArrayList<>();
for(char chr = 'a'; chr <= 'c'; chr++){
for (int j=0; j<5; j++){
alphabetList.add(chr);
}
}
您可能还想使用Collections.nCopies
以避免内部循环
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));
}
这篇关于将字母添加到列表Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文