简体   繁体   中英

SUM of elements of N Arrays using Java 8 Stream

I can have N arrays of different lengths. Important thing is that I don't know how many arrays I can have. Let's have a example with just 3 arrays:

Integer arr1[] = {5, 10, -5};
Integer arr2[] = {8, 3};
Integer arr3[] = {12, -1, 0, 9};

List<String> result = Arrays.stream(arr1)
        .flatMap(s1 -> Arrays.stream(arr2)
                .flatMap(s2 -> Arrays.stream(arr3)
                        .map(s3 -> s1 + s2 + s3)))
        .collect(Collectors.toList());

Is it possible to do such a thing for N Arrays, using Stream?

Here guys. Another example with the expected result

 Integer arr1[] = {2, 4, 5};
 Integer arr2[] = {2, 4, 5};
 Integer arr3[] = {2 , 4, 5};

 List<Integer> result = Arrays.stream(arr1)
                .flatMap(s1 -> Arrays.stream(arr2)
                .flatMap(s2 -> Arrays.stream(arr3)
                .map(s3 -> s1 + s2 + s3))).sorted().collect(Collectors.toList());

                 System.out.println(" List of results: "+result);


              // List of results: [6, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15]

This should work. We create a Stream of all arrays, then map the sum of those arrays as Integers and find the max value.

        int max = Stream.of(arr1, arr2, arr3)
                .map(array -> IntStream.of(array).sum())
                .max(Integer::compareTo)
                .orElseThrow(IllegalStateException::new);

Its not clear from your question what you want. So, we can only guess your problem and guess a solution. Please describe in words what you want to do. If your code is mostly incorrect, then you can expect people to give incorrect solutions. It looks like you want to find out the sum of N arrays. If yes, then here is the solution.

import java.util.Arrays;
import java.util.stream.Stream;

public class Temp {
    public static void main(String[] args) {
        Integer arr1[] = {5, 10, -5};
        Integer arr2[] = {8, 3};
        Integer arr3[] = {12, -1, 0, 9};

        System.out.println(doSomething(arr1, arr2, arr3));
    }

    public static Integer doSomething(Integer [] ... arrays){
        Integer sumOfArrays = Stream.of(arrays)
                .map( array -> Arrays.stream(array)
                        .reduce(0, (sum, nextInt) -> sum + nextInt )
                ).reduce( 0, (allArraySum, arraySum) -> allArraySum + arraySum );
        return sumOfArrays;
    }
}

If you want sum of all ints in arrays you can do like this:

int sumOfAll = Stream.of(arr1, arr2, arr3)
    .flatMap(Arrays::stream)
    .mapToInt(v -> v)
    .sum();

If you want a list with sum of ints on given position, then you can do like this. Compute max length in arrays and then use it to insert default value if current list is to small.

int max = Stream.of(arr1, arr2, arr3).mapToInt(a -> a.length).max().getAsInt();

List<Integer> reduce = Stream.of(arr1, arr2, arr3)
    .map(a -> Stream.of(a).collect(toList()))
    .reduce((a, b) -> IntStream.range(0, max)
        .mapToObj(i -> (i < a.size() ? a.get(i) : 0) + (i < b.size() ? b.get(i) : 0))
        .collect(toList()))
    .get();

UPDATE

If you want to achieve what you showed in the second example then it could be done like below.

  • Create List<List<Integer>> that collects all ints that are needed to summing.
  • Do the summing operation for every list.
List<List<Integer>> integersList = Stream.of(arr11, arr12, arr13)
        .map(a -> Stream.of(a).map(x -> Arrays.asList(x)).collect(toList()))
        .reduce((a, b) -> b.stream().flatMap(v -> a.stream()
                        .map(x -> {
                                    ArrayList<Integer> ints = new ArrayList<>(x);
                                    ints.add(v.get(0));
                                    return ints;
                                }
                        )
                ).collect(toList())
        ).get();

It gives:

[[2, 2, 2], [4, 2, 2], [5, 2, 2], [2, 4, 2], [4, 4, 2], [5, 4, 2], [2, 5, 2], [4, 5, 2], [5, 5, 2], [2, 2, 4], [4, 2, 4], [5, 2, 4], [2, 4, 4], [4, 4, 4], [5, 4, 4], [2, 5, 4], [4, 5, 4], [5, 5, 4], [2, 2, 5], [4, 2, 5], [5, 2, 5], [2, 4, 5], [4, 4, 5], [5, 4, 5], [2, 5, 5], [4, 5, 5], [5, 5, 5]]

Then summing it:

List<Integer> sum = integersList.stream()
        .map(a -> a.stream().reduce(Integer::sum).get())
        .sorted().collect(toList());

Final result:

[6, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM