Home > Mobile >  Find the sum of first elements of a 2d integer array
Find the sum of first elements of a 2d integer array

Time:08-07

There is an integer 2d array:

int[][] arr = {{3, 4},{5, 6, 7},{10, -4, 7}};

I want to find the sum of first elements: int sum = 3 5 10;

I can write:

int sum = 0;
for (final int[] i : arr)
    sum  = i[0];

But I want to find the sum without using traditional for loop.

I`ve tried reduce:

Arrays.stream(arr).reduce(0, (a, b) -> a[0]   b[0])

but it is not working

CodePudding user response:

try with this.

import java.util.*;
import java.util.stream.*;

public class Main
{
    public static void main(String[] args) {
        int[][] arr = {{3, 4},{5, 6, 7},{10, -4, 7}};
        
        int x = Arrays.stream(arr).map(vec -> vec[0]).reduce(0, Integer::sum);
        
        System.out.println(x);
    }
}

stream(arr) : takes array of arrays and returns a stream of arrays of arrays.

.map(vec -> vec[0]) : takes the lambda between parenthesis and executes it for every element in the stream, mapping the result in an output stream (it is an adapter). In this specific lambda we take the array and output the first element.

.reduce(0, Integer::sum) : it's the final consumer of the stream (also known as collectors). Takes a collector function (in this case the sum) so that all elements in the stream are collected in a summing variable starting from value 0 (the first parameter).

If I made any mistakes feel free to let me know in the replies

CodePudding user response:

what the issue here

Arrays.stream(arr).reduce(0, (a, b) -> a[0]   b[0])

the reduce mapper take 2 array and expect to return an array but you return an int

so another way to solve it by this

Arrays.stream(arr).mapToInt(a -> a[0]).sum()

first i mapped the int Array to int (first element of the array) then i used the sum for that stream

Edit: you can check this free tutorial from oracle for stream api https://dev.java/learn/the-stream-api/

hope that help and have a nice day :)

CodePudding user response:

As I explained in the comment, passing 0 as initial value for a is not a valid since 0[0] is not valid, therefore Your code is wrong.
You can do something like this:

Arrays.stream(arr).reduce(new int[] {0}, (a, b) -> new int[]{a[0] b[0] })[0];

Which reduces the 2d array into 1d array with one element that represents the sum and then prints its first element.

CodePudding user response:

Firstly, since there are subarrays of different sizes, it's worth to make sure that an element at index 0 exists, meaning that array isn't empty. Otherwise you might get ArrayIndexOutOfBoundsException.

Secondly, you don't need to use reduce here. In the Stream API we several specialized forms of reduction an action of obtaining the total sum of elements of a primitive stream is represented as a sum() operation (sure it's possible to use reduce() for that, but it makes your code unnecessarily verbose and less expressive).

Also, note that you might encounter integer overflow while adding the first element of each subarray together. To avoid that, if you have no clear constraints regarding the input, it makes sense to resort to LongStream.

int[][] arr = {{3, 4},{5, 6, 7},{10, -4, 7}};
    
long sum = Arrays.stream(arr)
    .filter(a -> a.length > 0)
    .mapToLong(a -> a[0])
    .sum();
  •  Tags:  
  • java
  • Related