将字母添加到列表 Java [英] Add alphabets to List Java

查看:47
本文介绍了将字母添加到列表 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);
            }
        }
    }
}

但我必须为更多字母添加多个 if 条件.有没有更好的方法来避免它.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆