有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java通过arraylist输出从高到低的数字?

有没有办法让我可以通过ArrayList输出对找到的最高数字和最低数字进行排序?我现在拥有的是一个“购物清单”,其设置如下:

public void addToBag(String anyItem, int anyUnits, double anyCost){
    int checkUnits = anyUnits;
    double checkCost = anyCost;
    if(checkUnits < 0 || checkCost < 0){
        System.out.println("You must enter a value equal to or greater than 0!");
    }else{
    shoppingBag.add(new Item(anyItem, anyUnits, anyCost));
}
}

和仅输出列表的输出

  public void calculateSalesReceipt(){
    System.out.println("Enter the sales tax percentage (ex. 0.08 for 8%) or type \"random\" for a random number: ");
    double tax = keybd.nextDouble();
    if(tax < 0){
        System.out.println("You must enter a value equal to or greater than 0!");
    }else{
    getPricePreTax();
    total = total;
    taxCost = total * tax;
    finaltotal = total + taxCost;
    System.out.println("Sales Receipt");
    System.out.println("-------------");
    for(Item currentProduct : shoppingBag){
        System.out.println(currentProduct.getName() + " - " + currentProduct.getUnits() + " units " + " - $" + currentProduct.getCost());
    }
    System.out.println("Total cost: $" + total);
    System.out.println("Total tax: $" + taxCost);
    System.out.println("Total cost with tax: $" + finaltotal);
    System.out.println("Do you have any coupons? Enter \"yes\" or \"no\"");
    String answer = keybd.next();
    if(answer.equals("yes")){
                applyCoupon();
            }else if(answer.equals("no")){
            System.out.println("Thank you!");
        }else if(answer != "yes" || answer != "no"){
            System.out.println("Thank you!");
        }
    System.out.println("Coupon discounts: $" + couponAmount);
    System.out.println("Grand total: $" + (finaltotal-couponAmount));
}
}

谢谢

编辑:

这样行吗

 public void getLargest(){
    for(Item currentProduct : shoppingBag){
        System.out.println(Collections.max());
    }
}

共 (3) 个答案

  1. # 1 楼答案

    使用Google Guava

    Function<Item, Double> itemCostFunction = new Function<Item, Double>() {
      @Override public Double apply(Item item) {
        return item.getCost();
      }
    };
    
    List<Item> sortedItems = Ordering.natural().onResultOf(itemCostFunction).sortedCopy(shoppingBag);
    

    现在

    Item biggest = Iterables.getLast(sortedItems);  // costliest
    Item smallest = sortedItems.get(0);  // cheapest 
    
  2. # 2 楼答案

    你想分类什么?成本

    你可以创建一个新类CostComparator实现Comparator<Item>,并根据价格比较Item

  3. # 3 楼答案

    你可能想要^{}(和Collections.min())。如果你想让整个列表按顺序排列,你可能需要Collections.sort()