Java lambda 循环累加求和

java 8 stream 提供了下面几种类型的求和

Stream::mapToInt
Stream::mapToDouble
Stream::mapToLong


	public void test() {
		List<Person> people = new ArrayList<>();
		people.add(new Person("zhangsan",20));
		people.add(new Person("lisi", 26));
		people.add(new Person("wangwu",35));
		
		int sum = people.stream()
		          .mapToInt(p -> p.getAge())
		          .sum();
		System.out.println("Total of ages " + sum);
	}

 但是没有BigDecimal类型,可以使用下面方法实现

    public void test() {
		List<Person> list = new ArrayList<>();
		list.add(new Person("zhangsan", 20, new BigDecimal(10.5)));
		list.add(new Person("lisi", 26, new BigDecimal(22.2)));
		list.add(new Person("wangwu", 35, new BigDecimal(15.54)));

		BigDecimal amounts = list.stream().map(item -> item.getAmount())
				.reduce(BigDecimal.ZERO, BigDecimal::add);
		amounts = amounts.setScale(1, BigDecimal.ROUND_UP);
		System.out.println("Total of amounts:" + amounts);

		// 或者
		BigDecimal sum = list
				.stream()
				.map(Person::getAmount)
				.reduce(BigDecimal::add)
				.get();
        sum = sum.setScale(1, BigDecimal.ROUND_UP);
		System.out.println("Total of sums: " + sum);
	}

 

    原文作者:我写的代码会爆炸
    原文地址: https://blog.csdn.net/angus_Lucky/article/details/85062728
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞