假設我有以下內容ArrayList<>:
ArrayList<Person> persons = new ArrayList<>();
這個類Person看起來像這樣:
public class Person {
String name;
int heightInCm;
int weightInKg;
// the class has the usual constructor, getters and setters
}
Personin的實體數量是可變的persons(意思persons.size()是不固定的)。
是否有一種簡單的方法(即使用類別庫工具)來計算例如 中heightInCm的平均值persons,或確定最大值,或最小值,或...?
我可以撰寫一些相當廣泛的代碼(使用多個回圈等)來完成這項作業,但肯定有一種內置的方式。提前致謝。
uj5u.com熱心網友回復:
您可以將流 API 與summarizingInt收集器一起使用。
它將回傳一個IntSummaryStatistics物件,其中包含計數、總和、最小值、最大值和平均值。
例子:
ArrayList<Person> persons = new ArrayList<>();
IntSummaryStatistics stat = persons.stream()
.collect(Collectors.summarizingInt(Person::getHeightInCm));
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/340896.html
