以下工具类方法基于Guava
List<Double>包装类型求值
- 求最大值
List<Double> list = ...;
Double max = Doubles.max(list.stream().mapToDouble(Double::valueOf).toArray());
Double max = Doubles.max(Doubles.toArray(list));
- 求最小值
List<Double> list = ..;
Double min = Doubles.min(list.stream().mapToDouble(Double::valueOf).toArray());
Double min = Doubles.min(Doubles.toArray(list));
- 求平均值
List<Double> list = ...;
Double average = list.stream().mapToDouble(Double::valueOf).average().getAsDouble();
List<User>对象类型求值
- 求User分数最大值
List<User> list = ...;
Double max = list.stream().mapToDouble(User::getScore).max().getAsDouble();
- 求User分数最小值
List<User> list = ...;
Double min= list.stream().mapToDouble(User::getScore).min().getAsDouble();
- 求User分数平均
List<User> list = ...;
Double average= list.stream().mapToDouble(User::getScore).average().getAsDouble();
其他用法
- 求List<Double>包装类型的中值
List<Double> list = ...;
// 先按升序排列集合
List<Double> transformList = Lists.newArrayList(list);
Ordering.usingToString();
Collections.sort(transformList);
// 取中值,list为偶数,取后面一个
Double middleValue = transformList.get(transformList.size()/2);
- 四舍五入,保留3位小数
double value = 1.23456;
double result = new BigDecimal(value).setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
输出:1.235