在 Java 8 中,Stream.reduce()
合并流的元素并产生单个值。
基本数据类型 和 包装类型 的一位数组求和
package test day1;import java.util.Arrays;public class Test {public static void main(String[] args) {// 基本数据类型 int long doubleint[] arr2 = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};int sum2 = Arrays.stream(arr2).sum();long[] arr3 = new long[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};long sum3 = Arrays.stream(arr3).sum();double[] arr5 = new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};double sum5 = Arrays.stream(arr5).sum();// 包装类型 Integer Long DoubleInteger[] arr4 = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};Integer sum4 = Arrays.stream(arr4).mapToInt(Integer::intValue).sum();Long[] arr6 = new Long[]{1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L};Long sum6 = Arrays.stream(arr6).mapToLong(Long::longValue).sum();Double[] arr7 = new Double[]{1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0};Double sum7 = Arrays.stream(arr7).mapToDouble(Double::doubleValue).sum();System.out.println("sum2 = " + sum2);System.out.println("sum3 = " + sum3);System.out.println("sum4 = " + sum4);System.out.println("sum5 = " + sum5);System.out.println("sum6 = " + sum6);System.out.println("sum7 = " + sum7);}
}
其中double求和会丢失精度,
可以使用如下办法解决:
将集合中Double对象转为BigDecimal对象在进行计算
result = list.stream().map(e->new BigDecimal(String.valueOf(e))).collect(Collectors.reducing(BigDecimal.ZERO, BigDecimal::add)).doubleValue();
代码示例:
package day1;import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;/*** @author lh* @date 2023/8/14 11:30 AM*/
public class TestBigDecimal1 {public static void main(String[] args) {double result = 0;List<Double> doubleList = new ArrayList<>(Arrays.asList(6.6, 1.3));Double sumD = doubleList.stream().mapToDouble(Double::doubleValue).sum();System.out.println(sumD); //丢失精度result = doubleList.stream().map(e->new BigDecimal(String.valueOf(e))).collect(Collectors.reducing(BigDecimal.ZERO, BigDecimal::add)).doubleValue();System.out.println(result);result = doubleList.stream().map(BigDecimal :: valueOf).collect(Collectors.reducing(BigDecimal.ZERO, BigDecimal::add)).doubleValue();System.out.println(result);result = doubleList.stream().map(BigDecimal::valueOf).reduce(BigDecimal::add).orElse(BigDecimal.ZERO).doubleValue();System.out.println(result);}}
结果:
7.8999999999999995
7.9
7.9
7.9