从数字列表中获取最大数量

时间:2015-06-18 20:14:44

标签: java

    public void getJustRevisionsNumberData(String duaNum) {
    List<Number> dua = new ArrayList<Number>();
    dua = getRevisionsNum(duaNum); 

    // dua object -> 123, 843, 455, 565
    // I want 843

    for(Number number : dua) {

        System.out.println(number);

    }
}

getRevisionsNum

    public List<Number> getRevisionsNum(String duaNum) {
    Session session = factory.openSession();

    AuditReader auditReader = AuditReaderFactory.get(session);
    return auditReader.getRevisions(DuaVO.class, duaNum);

我正在尝试获得最大数量但无法提出解决方案。有什么建议吗?

3 个答案:

答案 0 :(得分:2)

你可以跟踪到目前为止在另一个变量largestNumber中遇到的最大数字,然后一旦你遍历整个集合,你就可以用{{ 1}}在循环之外。

System.out.println(largestNumber)

double largestNumber = Double.MIN_VALUE; for(Number number: dua) { if(number.doubleValue() > largestNumber) largestNumber = number; } System.out.println(largestNumber); 设置为largestNumber可确保即使您处理的是非常大的负数,它们仍应满足Double.MIN_VALUE。在比较中调用number.doubleValue() > largestNumber是必要的,这样您就可以有两个.doubleValue()进行比较。

答案 1 :(得分:0)

听起来很简单! 这是一个我为一组整数工作的例子:

**  public int findMax(Collection<Integer> nums) {
    int temp = Integer.MIN_VALUE; // we want it to have the lowest value possible, else if we initialise it to 0 and the largest number is less than 0 it will not work.
    for (int i : nums) {// loop through the nums and we find the max number between temp and i and that is the new value of temp (So if i=10 and temp=1 then temp will be come 10)
        temp = Math.max(i, temp);
    }
    return temp;//we return the largest number found.
}

public int findMax(Collection<Integer> nums) {
    int temp = Integer.MIN_VALUE;
    for (int i : nums) {
        if(i > temp) temp = i;//similar with the code above, the only difference here is instead of calling a method over and over we perform a simple check and if it turns to be true (i is more than temp)  then temp gets the value of i.
    }
    return temp;
}**

希望能帮到你!

答案 2 :(得分:-1)

一种方法是您可以对集合进行排序,并选择第一个或最后一个数字(取决于您的排序方式)。但排序会损害性能。

您也可以遍历列表,如果新号码大于当前存储的号码,则会被替换。如:

public int getMax(ArrayList list){
    int max = Integer.MIN_VALUE;
    for(int i=0; i<list.size(); i++){
        if(list.get(i) > max){
            max = list.get(i);
        }
    }
    return max;
}

我相信这基本上就是Collections.max(yourcollection)的作用。

相关问题