user10824969
user10824969

Reputation:

How to find the sumOfelements in array of datatype

I have a custom class

class StackInfo {
    int start, size, capacity;
}

and to verify the total number of elements present in an array of such info I have

private int numberOfElements(StackInfo[] info) {
    int size = 0;
    for (StackInfo si : info) {
        size += si.size;
    }
    return size;
}

I tried converting it using streams to the following:

private int numberOfElements(StackInfo[] info) {
    return (int) Arrays.stream(info).map(s -> s.size).count();
    //       ^^ 
    //     to convert long
}

But the output for the above code is not correct either after casting as well.

Upvotes: 4

Views: 85

Answers (2)

fastcodejava
fastcodejava

Reputation: 41097

You can use reduce operation:

Arrays.stream(info).reduce((s1, s2) -> s1.size + s2.size);

Or the sum as @nullpointer has shown :

Arrays.stream(info).mapToInt(StackInfo::getSize).sum();

Upvotes: 2

Naman
Naman

Reputation: 31878

You seem to be looking for the sum operation and not count which would need you to convert the Stream to IntStream mostly. You can update your code to :

private int numberOfElementsStream(StackInfo[] info) {
    return Arrays.stream(info)    // Stream<StackInfo>
            .mapToInt(sd -> sd.size)   //IntStream of their size
            .sum();   // sum of all
}

Upvotes: 8

Related Questions