首页 > 解决方案 > 使用变量 String 或 char 作为对象名称

问题描述

int i = 0;
String alphabet = "abcdefghijklmnopqrstuvwxyz"; 
char letter = alphabet.charAt(i);

Letter a = new Letter(i,letter); Letter b = new Letter(i,letter); Letter c = new Letter(i,letter); Letter d = new Letter(i,letter); //...

名称在字母表中循环是否有更短的方法?

标签: java

解决方案


假设 Java 8(当引入了流时),如果我们可以Letter稍微简化构造函数并进行一个微小的假设,这将变得非常容易 -i代码中的变量只是字母的索引 - 在这种情况下,您可以计算它没有将它传递给构造函数(c - 'a'),因此我将在我的构造函数中省略它 - 它增加了很多不必要的噪音。

为了使我的答案更完整,让我们假设这是Letter我们将使用的类:

    public class Letter {
        char c; int index;

        public Letter(int c) {
            this.c = (char) c;
            this.index = c - 'a';
        }
    }

整个事情可以在一个oneliner中完成:

List<Letter> l = "abcdefghijklmnopqrstuvwxyz".chars().mapToObj(Letter::new).collect(Collectors.toList());

注释代码如下所示:

"abcdefghijklmnopqrstuvwxyz"        // Take the alphabet string
    .chars()                        // Turn the string into IntStream
    .mapToObj(Letter::new)          // Map all the characters into Letter constructor,
                                    // effectively transposing into stream of Letters
    .collect(Collectors.toList());  // Finally, collect all the Letters from the stream
                                    // into a list.

或者,如果您想获得一个数组,您可以使用.toArray();而不是.collect(...);


推荐阅读