java原生态查找数组最大值和最小值,以及使用Apache common-math实现

java原生态查找一个数组中的最小和最大值,相信不少人都懂,说白了就是迭代比较

public class FindMaxOrMinTest {
	public static void main(String[] args) {
		Double[] doubles = {2.1,1.1,5.4,10.0,-6.8};
		Double maxIndex = doubles[0];
		Double minIndex = doubles[0];
		for (int i = 0; i < doubles.length; i++) {
			if (maxIndex < doubles[i]) {
				maxIndex = doubles[i];
			}
			if (minIndex > doubles[i]) {
				minIndex = doubles[i];
			}
		}
		System.out.println("最大值:"+maxIndex+"\n最小值:"+minIndex);
	}
}

使用common-math,其jar包下载地址如下:
Download Apache Commons Math
创建一个lib,放置jar包,然后构建路径即可

直接上码

public class FindMaxOrMinTest {
	public static void main(String[] args) {
		Double[] doubles = {2.1,1.1,5.4,10.0,-6.8};
		
		//使用common-math
		DescriptiveStatistics statistics = new DescriptiveStatistics();
		for (int i = 0; i < doubles.length; i++) {
			statistics.addValue(doubles[i]);
		}
		Double maxIndex = statistics.getMax();
		Double minIndex = statistics.getMin();
		System.out.println("最大值:"+maxIndex+"\n最小值:"+minIndex);
	}
}

虽然看起来比没有比原生态简单多少,但是该描述性统计类DescriptiveStatistics还有很多非常好的方法,能够快速获得方差,标准差,中位数,百分位数等等,当然common-math还可以用来计算简单回归,最小二乘回归等等,小编只是给大家打开一扇窗,能看多远就靠大家了。(根据官方网站说法,这些方法都优化过,执行时占用内存更少了)

既然它都这么说了,小编也作死地进去看了一下源码(。。还行。。)

    /**
     * Returns the maximum of the available values
     * @return The max or Double.NaN if no values have been added.
     */
    public double getMax() {
        return apply(maxImpl);
    }

进去发现getMax是原来调用该方法,接着找呀找呀

   @Override
    public double evaluate(final double[] values, final int begin, final int length)
    throws MathIllegalArgumentException {
        double max = Double.NaN;
        if (test(values, begin, length)) {
            max = values[begin];
            for (int i = begin; i < begin + length; i++) {
                if (!Double.isNaN(values[i])) {
                    max = (max > values[i]) ? max : values[i];
                }
            }
        }
        return max;
    }

所以呢,本质还是迭代比较,不过呢 max = (max > values[i]) ? max : values[i];这么高大尚的写法,小编是知道,不过没有这个习惯使用,看来小编还是属于入门级别。

(小编能力有效,仅供参考,莫怪!)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值