如何在Java中映射数组?

时间:2018-09-20 01:46:50

标签: java arrays

我有一个字符串数组

String[] suffixes = getSuffixes();

,我想要一个基于旧数组的新数组,并附加一个前缀。我会在Ruby,JavaScript,Perl,Lisp等中执行以下操作:

// pseudocode for what I would like

String[] full_words = suffixes.map(suffix => "re" + suffix);

在我的应用程序中,我仅限于数组。 (这只是学校作业的一小部分,不允许我使用Collections库。)在Java 8中有任何方法可以做到这一点吗?

1 个答案:

答案 0 :(得分:3)

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循环的讨论-它与要输入的行数或字符无关,也许我也对具有高阶函数的语言宠爱不已,但对我来说却存在精神上的隔disconnect在转换集合(这只是地图所做的事情)与使大脑进入其大小以及如何获取/分配元素的细节之间。 同样值得一提的是,Java流框架仍然落后。