# Stream聚合函数

## 记录小朋友

@Getter
@Setter
@NoArgsConstructor
public class Child {

private int age;         //年龄
private String firstName; //名
private String lastName; //姓
private String fullName; //全名

Child(int age, String lastName, String firstName) {
this.age = age;
this.lastName = lastName;
this.firstName = firstName;
this.fullName = lastName + firstName;
}
}


@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class ClassBook {
private String name = "Stream班名册"; //班名册记录
private List<Child> kids = new LinkedList<>();//名册表
}


public class StreamMathApiTest {
private ClassBook book;
@Before
public void __setUp() {
this.book = new ClassBook("Stream班名册", allChild);
}
}


## 计算总学生(Count)

@Test
public void test_count() {
//count 函数
long count = this.book.getKids().stream().
count();

Assert.assertTrue(count == 10l);
}


## 计算平均年龄(mapTo(xxx) + Avgage)

@Test
public void test_avg() {
double avgAge = this.book.getKids().
stream().
mapToDouble(Child::getAge).
average().orElse(0l);

Assert.assertEquals("Error calc!", "3.45", Double.toString(avgAge));
}


## 计算最大/小值(Max/Min)

@Test
public void test_max() {
//最大值
Child maxChild = this.book.getKids().stream().
max((o1, o2) -> {
//借助BigDecimal函数来比较，也可以把Float转成int来进行比较，方法很多种。
BigDecimal first = new BigDecimal(String.valueOf(o1.getAge()));
BigDecimal second = new BigDecimal(String.valueOf(o2.getAge()));
return first.compareTo(second);
}).get();

Assert.assertEquals("欧阳峰", maxChild.getFullName());

//最小值 返回过来即可
Child minChild = this.book.getKids().stream().
max((o1, o2) -> {
BigDecimal first = new BigDecimal(String.valueOf(o1.getAge()));
BigDecimal second = new BigDecimal(String.valueOf(o2.getAge()));
return second.compareTo(first);
}).get();
Assert.assertEquals("萧峰", minChild.getFullName());
}


## 累加(reduce)

@Test
public void test_reduce() {
Float totalAge = this.book.getKids().stream().
map(Child::getAge)
.reduce(0f, Float::sum);

//Double::sum/Interge::sum/......

Assert.assertEquals(totalAge.toString(), "34.5");
}



posted @ 2021-09-28 23:25  乌托拉赛文  阅读(581)  评论(1编辑  收藏  举报