BigDecimal:
1
|
BigDecimal bb =list.stream().map(Plan::getAmount).reduce(BigDecimal.ZERO,BigDecimal::add);
|
int、double、long:
1
|
double max = list.stream().mapToDouble(User::getHeight).sum();
|
补充:java8-Stream流之数值函数(求和、最大值、最小值、平均值)
我就废话不多说了,大家还是直接看代码吧~
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
//todo stream流的使用
//todo filter:过滤操作;保留符合过滤条件的对象;这是一个中间操作;后面可以带最终操作
//todo mapToInt: 将数据根据double类型来处理;
public static void main(String[] args) {
List<SalesOrder> list = createSalesOrder();
//获取集合中城市为上海的数量
System.out.println( "mapToInt获取和:" +list.stream().filter(s -> s.getConsigneeCity().equals( "上海" ))
.mapToInt(SalesOrder::getCreateUserId).sum());
//利用stream流中的函数获取相关数值信息
IntSummaryStatistics summaryStatistics = list.stream().filter(s -> s.getConsigneeCity().equals( "上海" ))
.mapToInt(SalesOrder::getCreateUserId).summaryStatistics();
System.out.println( "summaryStatistics函数获取数量:" +summaryStatistics.getCount());
System.out.println( "summaryStatistics函数获取平均值:" +summaryStatistics.getAverage());
System.out.println( "summaryStatistics函数获取最大值:" +summaryStatistics.getMax());
System.out.println( "summaryStatistics函数获取最小值:" +summaryStatistics.getMin());
System.out.println( "summaryStatistics函数获取和" +summaryStatistics.getSum());
}
static List<SalesOrder> createSalesOrder(){
List<SalesOrder> list = new LinkedList<>();
SalesOrder salesOrder = new SalesOrder();
salesOrder.setCreateUserId( 12 );
salesOrder.setConsigneeCity( "上海" );
list.add(salesOrder);
salesOrder = new SalesOrder();
salesOrder.setConsigneeCity( "上海" );
salesOrder.setCreateUserId( 24 );
list.add(salesOrder);
salesOrder = new SalesOrder();
salesOrder.setConsigneeCity( "北京" );
salesOrder.setCreateUserId( 18 );
list.add(salesOrder);
salesOrder = new SalesOrder();
salesOrder.setConsigneeCity( "深圳" );
salesOrder.setCreateUserId( 16 );
list.add(salesOrder);
salesOrder = new SalesOrder();
salesOrder.setConsigneeCity( "广州" );
salesOrder.setCreateUserId( 30 );
list.add(salesOrder);
salesOrder = new SalesOrder();
salesOrder.setConsigneeCity( "杭州" );
salesOrder.setCreateUserId( 40 );
list.add(salesOrder);
return list;
}
|
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。如有错误或未考虑完全的地方,望不吝赐教。
原文链接:https://invincible.blog.csdn.net/article/details/95994908