A_E*_*ric 1 java collections average
所以假设我有一个简单的对象:
public class Items {
private static int
numItems,
itemsInStock,
itemsSold,
//...
}
Run Code Online (Sandbox Code Playgroud)
在代码的其他地方我有一个 ArrayList<Items>
如果有一种简单的方法可以获得 numItems / ItemsInStock 等的平均值/中位数,而无需在对象的每个字段上执行 for/each?
当前代码如下:
for (Items item: allItems) {
if (item.field != null) {
temp += item.field;
}
}
fieldAvg = temp / allItems.size();
Run Code Online (Sandbox Code Playgroud)
使用流可以说更优雅:
double avg = allItems.stream().mapToInt(i -> i.itemsInStock).average().getAsDouble();
// Or any other field -------------------------^
Run Code Online (Sandbox Code Playgroud)
您可以使用IntSummaryStatistics,其所有的功能Average,Sum,Max,..:
int[] itemsInStock = allItems.stream().mapToInt(Items::getItemsInStock).toArray();
IntSummaryStatistics stat = IntStream.of(itemsInStock).summaryStatistics();
double average = stat.getAverage();
int max = stat.getMax();
int min = statistics.getMin();
long count = statistics.getCount();
long sum = statistics.getSum();
....
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
207 次 |
| 最近记录: |