1 回答
TA贡献1848条经验 获得超10个赞
String [] full_suffixes = Arrays.stream(suffixes)
.map(suffix -> "re" + suffix)
.toArray(size -> new String[size])
“老式”循环太冗长了:
String [] full_suffixes = new String[suffixes.length];
for(int i = 0; i < suffixes.length; i++) {
full_suffixes[i] = "re" + suffixes[i];
}
要解决“太快”的评论:
import java.util.Arrays;
public class Test {
static int N = 10000;
public static void main(String [] args) throws Exception {
if(args.length > 0) {
N = Integer.parseInt(args[0]);
}
String [] array = new String[100000];
for(int i = 0; i < array.length; i++) {
array[i] = "abcdef" + i;
}
long start = System.currentTimeMillis();
fancy(array);
System.err.println("Fancy took " + (System.currentTimeMillis() - start) + "ms");
start = System.currentTimeMillis();
oldSchool(array);
System.err.println("Loop took " + (System.currentTimeMillis() - start) + "ms");
}
public static void fancy(String [] array) {
for(int i = 0; i < N; i++) {
String [] full_suffixes = Arrays.stream(array)
.map(suffix -> "re" + suffix)
.toArray(size -> new String[size]);
}
}
public static void oldSchool(String [] array) {
for(int i = 0; i < N; i++) {
String [] full_suffixes = new String[array.length];
for(int j = 0; j < array.length; j++) {
full_suffixes[j] = "re" + array[j];
}
}
}
}
运行(jdk 1.8.0_60):
$ java Test 100
Fancy took 502ms
Loop took 398ms
$ java Test 1000
Fancy took 3067ms
Loop took 2227ms
$ java Test 5000
Fancy took 13288ms
Loop took 11494ms
$ java Test 10000
Fancy took 27744ms
Loop took 27446ms
我不会说这更快,但不幸的是,在当前的流框架实现中,性能和代码清晰度之间存在权衡。
编辑:为了解决关于 map 与 for 循环的讨论——这与要输入的行数或字符数无关,也许我也被具有高阶函数的语言所宠坏,但对我来说,转换 a集合(这就是 map 的作用)并将我的大脑放入其大小以及如何获取/分配元素的细节中。另外值得一提的是,Java 流框架仍然落后。
添加回答
举报