将字母添加到列表 Java

huangapple go评论81阅读模式
英文:

Add alphabets to List Java

问题

我想创建一个包含每个字母出现5次的字母表列表我尝试了一段代码它有效地工作了

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

但是如果要添加更多字母我将不得不添加多个条件语句有没有更好的方法来避免这种情况
英文:

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&lt;Character&gt; alphabetList = new ArrayList&lt;&gt;();
        for (int i=0; i&lt;3; i++){
            char chr=&#39;a&#39;;
            if (i==1)
                chr = &#39;b&#39;;
            if (i==2)
                chr = &#39;c&#39;;
            for (int j=0; j&lt;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

得分: 1

你可以像下面这样使用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来避免内部循环:

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

You can use char loop as below,

List&lt;Character&gt; alphabetList = new ArrayList&lt;&gt;();
    for(char chr = &#39;a&#39;; chr &lt;= &#39;c&#39;; chr++){
        for (int j=0; j&lt;5; j++){
            alphabetList.add(chr);
    }
}

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

for(char chr = &#39;a&#39;; chr &lt;= &#39;c&#39;; chr++){
    alphabetList.addAll(Collections.nCopies(5, chr));
}

huangapple
  • 本文由 发表于 2020年4月4日 19:20:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/61027316.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定