Using streams / functional programming for multiple arrays in Java 8

I have 2 arrays y

and z

I want to return an integer array whereresult[i] = y[i] - z[i]

Here's the code:

static int[] join(int[] y, int[] z) {
    int[] result = new int[Math.min(y.length, z.length)];
    for(int i = 0; i < result.length; ++i) {
        result[i] = y[i] - z[i];
    }
    return result;
}

      

However, I want to do the same using Java 8 technologies for functional programming such as streams. However, all stream functions I know only work for one list at a time.

How can i do this?

Edit Also how can I do the same as I mentioned, but instead want to return a boolean array where:result[i] = y[i] == 5 || z[i] == 10

+3


source to share


2 answers


You can use IntStream

to simulate iteration using a counter variable:



static int[] join(int[] y, int[] z) {
    int min = Math.min(y.length, z.length);
    return IntStream.range(0, min).map(i -> y[i] - z[i]).toArray();
}

      

+5


source


static int[] join(int[] y, int[] z) {
    int[] result = new int[Math.min(y.length, z.length)];
    for(int i = 0; i < result.length; ++i) {
        result[i] = y[i] - z[i];
    }
    return result;
}

      

A shorthand way to do this is to replace the for loop with the following:

    Arrays.setAll(result, i -> y[i] - z[i]);

      



Unfortunately, there is no way to do this if the result is boolean[]

, since primitive specializations for Arrays.setAll

are only provided for regular ones int

, long

and double

.

But there is no magic here; Arrays.setAll

just uses IntStream.range()

to implement an aggregate operation on all array indices. Thus:

static boolean[] join(int[] y, int[] z) {
    boolean[] result = new boolean[Math.min(y.length, z.length)];
    IntStream.range(0, result.length)
             .forEach(i -> result[i] = y[i] == 5 || z[i] == 10);
    return result;
}

      

+3


source







All Articles