java - 使用变量 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 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(...);
推荐阅读
- apache-spark - 如何使用 Spark SQL Scala API(不是 SQL)检查 Hive 表是否为外部表
- flutter - 如何在没有包的情况下在 Flutter 中实现下拉列表?
- jquery - http_request_duration_seconds_sum / http_request_duration_seconds_count 显示 2 个图表
- cross-browser - Blob PDF 数据未在 IE 11 中呈现
- db2 - 获取 11424 行后,源限定符中的 Informatica SQL30081N 出现错误
- c# - Xamarin Android 模拟器显示黑屏
- c# - 验证文本字段的前 2 个字符,后跟 4 个 int
- ios - 如何在 Swift 中删除我的位置的注释?我只想要一个脉动的点
- css - 如何优先选择我的样式表而不是 REACT 中的引导程序(包含在 index.js 文件中)?
- laravel - 如何使用 Composer 安装 lumen 5.8