java - 如何使用stream#sorted()按Java 8中两个字段的乘积进行排序

标签 java sorting java-stream

我刚开始在 Java 8 中使用 lambda,并且在排序时遇到问题。

基本上,我在一个类中有 4 个字段,然后在我的 main 方法中创建一个要排序的对象数组。我希望能够使用Stream#sorted()按 2 个字段的乘积(价格 * 数量)对输出进行排序。

这是我要排序的类:

public class Invoice {

   private final int partNumber; 
   private final String partDescription;
   private int quantity;
   private double price;

   // constructor
   public Invoice(int partNumber, String partDescription, int quantity, double price) {
      if (quantity < 0) // validate quantity
         throw new IllegalArgumentException("Quantity must be >= 0");

      if (price < 0.0) // validate price
         throw new IllegalArgumentException("Price per item must be >= 0");

      this.partNumber = partNumber;
      this.partDescription = partDescription;
      this.quantity = quantity;
      this.price = price;
   } // end constructor

//get and set accessors 

}

这是我的测试类和对象数组:

public class ProcessInvoices  {

    public static void main(String[] args) {

      //declare array of invoice objects
      Invoice[] invoices = {
        new Invoice(83, "Electric sander", 7, 57.98),
        new Invoice(24, "Power saw", 18, 99.99),
        new Invoice(7, "Sledge hammer", 11, 21.50),
        new Invoice(77, "Hammer", 76, 11.99),
        new Invoice(39, "Lawn mower", 3, 79.50),
        new Invoice(68, "Screw driver", 106, 6.99),
        new Invoice(56, "Jig saw", 21, 11.00),
        new Invoice(3, "Wrench", 34, 7.50)};

      System.out.println("\nInvoices mapped to description and invoice amount");
      Arrays.stream(invoices)
        .sorted(Comparator.comparing(invoice.getQuantity() * invoice.getPrice()))
        .map(invoice -> String.format("Description: %-15s     Invoice amount:  $%,6.2f", invoice.getPartDescription(), (invoice.getQuantity() * invoice.getPrice())))
        .forEach(invoice -> System.out.printf("%s%n", invoice));

}

在流中,我将 partDescription 映射到 quantityprice 的乘积,该乘积给出了发票的总价格。这就是我想要排序的依据,即发票的总价,但我不知道使用 sorted() 方法执行此操作的正确方法。

我尝试简单地按数量 * 价格进行比较,但这告诉我变量“发票无法识别”。如果我尝试在 map() 语句之后进行排序,那也不起作用。我还尝试过使用不同的变量 amount,但也没有运气。

如何使用 sorted() 按两个字段的乘积进行排序?

最佳答案

您的比较器 lambda 中有错误,它应该显示为

.sorted(Comparator.comparing(invoice -> invoice.getQuantity() * invoice.getPrice()))

而不是

.sorted(Comparator.comparing(invoice.getQuantity() * invoice.getPrice()))

通知缺少发票 ->

关于java - 如何使用stream#sorted()按Java 8中两个字段的乘积进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42283708/

相关文章:

java - 不同种类的类继承自android java中的抽象类

algorithm - 映射排序索引

c - 在 C 中修剪 int 数组以进行桶排序

Java 8 收集对象中已经存在的列表

Java在列+行的多维数组中打印unicode字符?

java - 我需要删除 ArrayList 中可能出现多次的特定元素

java - Dr java中的java错误

algorithm - 根据#followers #following 推特用户的 "importance"值的等式

java - Java8-Streams 中的 GroupingBy

Java 8 映射到对象列表,其中一个字段分组为一个列表