[英]How to sum the values in List<int[]> using Java 8
我想使用 Java 8 找到List<int[]>
的總和。這是我的嘗試。
int sum = counts.stream().flatMap(i -> Stream.of(i).mapToInt(m)).sum();
但是,我收到錯誤無法轉換為Stream<Object>
到<unknown>
。
您想要flatMap
到IntStream
。 之后,取總和很容易。
int sum = counts.stream()
.flatMapToInt(IntStream::of)
.sum();
int sum = counts.stream().flatMapToInt(array -> IntStream.of(array)).sum();
你的i
是一個原始數組( int[]
),所以Stream.of(i)
將返回一個Stream<int[]>
。
我建議您首先計算每個單獨數組的總和,然后對所有數組求和:
int sum=counts.stream()
.mapToInt(ar->IntStream.of(ar).sum()) // convert each int[] to the sum
// of that array and transform the
// Stream to an IntStream
.sum(); // calculate the total sum
你可以這樣做:
int sum = counts.stream() // getting Stream<int[]>
.mapToInt(a -> Arrays.stream(a).sum()) // getting an IntStream with the sum of every int[]
.sum(); // getting the total sum of all values.
這對我有用:
int sum = counts.stream().mapToInt(i -> Arrays.stream(i).sum()).sum();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.