【问题标题】:How do I print an array of objects sorted by a property? [duplicate]如何打印按属性排序的对象数组? [复制]
【发布时间】:2020-03-06 00:03:44
【问题描述】:

我正在尝试打印按属性排序的对象数组,在本例中为 partDescription。我正在尝试使用流。


    public class ProcessInvoices {
       public static void main(String[] args) {
          List<Invoice> invoices = Arrays.asList(
             new Invoice("83", "Electric sander", 7, 57.98),
             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", "Screwdriver", 106, 6.99),
             new Invoice("56", "Jig saw", 21, 11.00),
             new Invoice("3", "Wrench", 34, 7.50)
          );
          List result = invoices.stream(partDescription).sorted().collect(Collectors.toList());
          System.out.println(result);
       }
    }

还有发票类:


    public class Invoice {
       private final String partNumber; 
       private final String partDescription;
       private int quantity;
       private double pricePerItem;

       public Invoice(String partNumber, String partDescription, int quantity,
          double pricePerItem) {
          this.quantity = quantity;
          this.partNumber = partNumber;
          this.partDescription = partDescription;
          this.pricePerItem = pricePerItem;
       } 

【问题讨论】:

    标签: java arrays sorting java-stream


    【解决方案1】:

    找到了我正在寻找的答案。我需要使用:

    
          List result = invoices.stream().sorted(Comparator.comparing(Invoice::getPartDescription)).collect(Collectors.toList());
          System.out.println(result);
    
    

    【讨论】:

    • 那应该是一个发票列表> List。很好地自己找到解决方案!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-05
    • 2023-03-13
    • 2016-11-25
    • 1970-01-01
    • 1970-01-01
    • 2014-09-17
    • 1970-01-01
    相关资源
    最近更新 更多