list排序的问题

1.需求,找出list对象中某个属性最大的
2.我的实现
 private Double getMaxUpperrangeLimit()
    {
        ParametersPoolInterface parameterPool = RequestContext.getPool();
        ListSensorParameter listSensorLp = (ListSensorParameter)parameterPool.getParameter(ParameterNames.LIST_SENSOR_LP);
        List<Sensor> sensorLpList = listSensorLp.getSensorList();
        if(sensorLpList == null || sensorLpList.size() < 1)
        {
            return null;
        }
        Collections.sort(sensorLpList, new Comparator<Sensor>()
                {
                    public int compare(Sensor o1, Sensor o2)
                    {
                        double v = o1.getUpperrangeLimit() - o2.getUpperrangeLimit();
                        if (v < 0)
                        {
                            return 1;
                        } else if (v > 0)
                        {
                            return -1;
                        } else
                        {
                            return 0;
                        }
                    }
                });
        return sensorLpList.get(0).getUpperrangeLimit();
    }


3.manager的实现
    private Double getMaxUpperrangeLimit()
    {
        ParametersPoolInterface parameterPool = RequestContext.getPool();
        ListSensorParameter listSensorLp = (ListSensorParameter)parameterPool.getParameter(ParameterNames.LIST_SENSOR_LP);
        List<Sensor> sensorLpList = listSensorLp.getSensorList();
        if (sensorLpList == null || sensorLpList.size() < 1)
        {
            return null;
        }
        Double max = sensorLpList.get(0).getUpperrangeLimit();
        for (int i = 1; i < sensorLpList.size(); i++ )
        {
            Double tmp = sensorLpList.get(i).getUpperrangeLimit();
            if (tmp > max)
            {
                max = tmp;
            }
        }
        return max;
    }


总结:我的写法缺点是把list原来的顺序给改变了,这就涉及到面试中常用的一个情况,不需要改变值的时候,可以讲这个list赋值给给另外一个list,然后再对另外一个list进行操作,算是用一个临时变量去操作!而且取一个最大值,只要遍历一次就可以了。

你可能感兴趣的:(list排序)