简体   繁体   中英

Java map / collect for Stream to sum List of Lists

I am using Java 8, and the Map,Reduce,Collect APIs from the package java.util.stream . I have a use case where I need to vertically sum a list of list. The structure of my list is List<List<Integer>> I just can't think of a way where I could squash the internal Lists using the map, and reduce or collect operations available on the stream. Consider the following code. Say my list is named transactions . What this transaction stores is the quantity of items sold in each transaction for each item in the internal list. The length of the internal list is the same for all transactions, because it contains one entry of each item in the inventory. If the item was not involved in the transaction it just stores 0.

I was thinking something on the lines of

transaction.stream().map(
      /*Try and put sum into an accumulator List*/
).collect(
      /*Collect entries into a list*/
)

I just couldn't figure how to materialize this in code. All the resources on the web are trivial examples not working on collection objects. Any pointers/tips will be much appreciated.

Because you have a List<List<Integer>> , it seems that a vertical sum should produce a List<Integer> , as each column will have its own sum. Assuming every row in the List<List<Integer>> contains the same number of elements, it would be a good idea to first find the transpose of the List<List<Integer>> , sum every row, and collect it back into a List<Integer> . You can do it using the following:

List<List<Integer>> list = Arrays.asList(
    Arrays.asList(1, 2, 3, 4),
    Arrays.asList(5, 6, 7, 8)
);

List<Integer> sumList = IntStream.range(0, list.get(0).size())
                                 .mapToObj(i -> list.stream()
                                                    .mapToInt(l -> l.get(i))
                                                    .sum())
                                 .collect(Collectors.toList());

System.out.println(sumList);

Output:

[6, 8, 10, 12]

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