【问题标题】:Sorting list of objects according the changeable object field根据可变对象字段对对象列表进行排序
【发布时间】:2020-11-04 18:02:44
【问题描述】:

我有一个产品列表。我想根据数量对产品进行递减排序。

public class Product {
    String name;
    int quantity;
    Product(String name, int quantity) {
        this.name=name;
        this.quantity=quantity
    }
}

默认情况下,列表中有 4 个产品,数量为 0。

List<Product> products = new ArrayList();
products.add(new Product("Book",0));
products.add(new Product("Table",0));
products.add(new Product("Chair",0));
products.add(new Product("Pen",0));

此外,用户可以通过 Web UI 逐一递增或递减数量(通过单击每个产品旁边的递增或递减按钮)

例如,如果用户增加“Pen”产品数量,则“Pen”产品应重新定位到列表顶部。

每一个递增或递减过程,我都需要重新排序列表。但是,在每次递增或递减过程中运行排序算法是非常低效的,尤其是当列表中有很多项目时。

我还没有使用任何排序算法。但是我相信,如果列表中的项目太多并且仅增加了一个产品,那么所有列表都必须重新排序。我认为,这是低效的,所以我问这种问题是否有另一种方法。

那么,如何对这种列表进行排序呢?

【问题讨论】:

  • 这是什么语言?排序代码在哪里(我假设您有这样的代码并且您已经对其进行了基准测试并发现它“慢”)?
  • @auburg 它是 Java。我还没有使用任何排序算法。但我相信,如果列表中的项目太多并且仅增加一个产品,那么所有列表都必须重新排序。我认为,这是低效的,所以我问这种问题是否有另一种方法。
  • 请阅读:stackify.com/premature-optimization-evil - 除非您将拥有数十万种产品,否则即使担心性能也是毫无意义的。每次对一些产品重新分类的运行时间成本可以忽略不计。
  • 只有在遇到问题时才担心优化,然后才在 profiling 之后。

标签: java sorting


【解决方案1】:

Java 8 排序列表的方式。内部是归并排序。

    products.sort(Comparator.comparing(Product::getQuantity).reversed());

或

    products.sort(Comparator.comparing(Product::getQuantity, Comparator.reverseOrder()));

流示例

products.stream()
                .sorted(Comparator.comparing(Product::getQuantity, Comparator.reverseOrder()))
                .forEach(System.out::println);

【讨论】:

    【解决方案2】:

    我们在Collections 类中有一个sort 方法,可以使用ASC 对产品进行排序,例如:

    Collections.sort(products, Comparator.comparing(Product::getQuantity)); 
    

    对于DESC,我们需要调用reversed方法:

    Collections.sort(products, Comparator.comparing(Product::getQuantity).reversed());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-03
      • 2012-05-19
      • 2013-03-28
      • 2022-01-11
      • 2019-08-18
      • 2015-03-30
      相关资源
      最近更新 更多