Java:如何获得最高和最高文件中的最低值

时间:2017-11-09 11:50:11

标签: java arraylist

问题解决了

我想从文件中找到最高和最低值。 我已将文件中的数字从String转换为double。如果我想使用Get方法查找最高和最低金额,我该怎么办?

5 个答案:

答案 0 :(得分:1)

编辑:我完成了原来答案的混乱,因为我没有意识到Strings将通过使用标准Collections()类方法按字典顺序进行比较

因此,使用Collections()执行此操作的最佳方法是创建自定义Comparator

Comparator<String> sort = (o1, o2) -> Double.valueOf(o1).compareTo(Double.valueOf(o2));
String max = Collections.max(numList, sort);
String min = Collections.min(numList, sort);

Try it online!

答案 1 :(得分:1)

你应该在从文件中读取时将数据放入arraylist。 然后使用merge或quick开始对数字进行排序。

我正在使用inbuild Collections.sort()方法。

public static void main(String[] args) {
    ArrayList<String> Argument = new ArrayList<String>();       

    for (String item: args) {
        Argument.add(item);         
    }

    for (int i=0;i<args.length;i++) {
        if (args[i].trim().equals("-H")) {
            i++;
            thatname = Argument.get(i);
            i++;
            thatage = Argument.get(i);
            Human person = new Human(thatname,thatage);
            System.out.println(person.getName()+"  "+person.getAge());
        }

这可以解决您的问题。

答案 2 :(得分:0)

Double higher = 0;
Double lower = 0;
for (String item:numList)
        { 
            Double result = Double.parseDouble(item);
            if (result>higher) { higher = result;}
            if (result<lower) { lower = result;}
            //Calculate the total sales for each week
            total += result;
        }

答案 3 :(得分:0)

public static double getMin(List<String> list) {
    double min = Double.MAX_VALUE;
    for (String s : list) {
        double d = Double.valueOf(s);
        min = min > d ? d : min;
    }
    return min;
}

public static double getMax(List<String> list) {
    double max = Double.MIN_VALUE;

    for (String s : list) {
        double d = Double.valueOf(s);
        max = max < d ? d : max;

    }
    return max;
}

Java8示例:

public static double getMinJ8(List<String> list) {
    return list.stream().map(s -> Double.valueOf(s)).min((d1, d2) -> d1.compareTo(d2)).get();
}
public static double getMaxJ8(List<String> list) {
    return list.stream().map(s -> Double.valueOf(s)).max((d1, d2) -> d1.compareTo(d2)).get();
}

答案 4 :(得分:0)

将所有值存储在treeset中,以便对所有元素进行排序。 现在使用firstlast

示例代码

    TreeSet s=new TreeSet();
    //add elements to the set
    s.add(100);
    s.add(200);
    s.add(1);
   // use first() method to get the lowest
    System.out.println(s.first());
   //use last method to get the highest
    System.out.println(s.last());

输出:1

200

相关问题