Java lambda 方法使用(2)

统计相关的操作

List list = Lists.newArrayList("1","2","3","4","5","6","7","8","9","10");
		
IntSummaryStatistics collect = list.stream().collect(Collectors.summarizingInt(Integer::valueOf));
long sum = collect.getSum();//和
long count = collect.getCount();//计数
double average = collect.getAverage();//平均值
int max = collect.getMax();//最大值
int min = collect.getMin();//最小值

System.out.printf("sum = %d,count=%d,average = %f,min=%d,max%d\n", sum,count,average,min,max);


BinaryOperator accumulator = (x,y) -> x.concat(y);
String reduce = list.stream().reduce("start:", accumulator);
System.out.println(reduce);//start:12345678910

Optional reduce2 = list.stream().reduce(accumulator);
System.out.println(reduce2);//Optional[12345678910]

Integer reduce3 = Stream.of(1,2,3,4,5,6,7,8,9,10).reduce(0, (x,y) -> x + y);
System.out.println(reduce3);

Integer reduce4 = Stream.of(1,2,3,4,5,6,7,8,9,10).reduce(0,  (x,y) -> x + y,  (x,y) -> x + y);
System.out.println(reduce4);

你可能感兴趣的:(java)