我正在尝试找到最快、最有效的方法来基于自定义可比较实现获取对象 arrayList 中的前 K 个项目。
在我的研究过程中,有人建议我应该使用最大/最小堆,它在java中被抽象为PriorityQueue。但是,问题是我不知道如何在对象的 arrayList 上实现它
这是我的对象实例
public class PropertyRecord {
private long id;
private String address, firstName, lastName, email, ownerAddress;
private LocalDate dateSold;
private BigDecimal price;
public PropertyRecord(long id, String address, String firstName, String lastName, String email, String ownerAddress, LocalDate dateSold, BigDecimal price) {
this.id = id;
this.address = address;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.ownerAddress = ownerAddress;
this.dateSold = dateSold;
this.price = price;
}
//getters and setters...
}
我想根据价格获取前 k 个商品。我已经编写了一个方法(见下文),它采用 arrayList 和 K(获取前 K 个项目)并使用 StreamAPI,但我知道这不是最有效的方法,因为这将对整个列表进行排序,即使我只想要前 K 项。所以我想要的不是 O(n),而是 O(k log n)。
//return the top n properties based on sale price.
public List<PropertyRecord> getTopProperties(List<PropertyRecord> properties, int n){
//using StreamAPI
return properties.stream()
.sorted((p1, p2) -> p2.getPrice().compareTo(p1.getPrice()))
.limit(n)
.collect(Collectors.toList());
}
请问有什么帮助吗?
最佳答案
Guava 包含 TopKSelector正是可以做到这一点的类。
在最新的 Guava 版本中,此功能现在公开为 Comparators.greatest()
.
但是,如果您不局限于使用 ArrayList
进行存储,那么您最好使用 PriorityQueue
这自然会使元素保持优先顺序。
关于java - Java 获取数组列表中前 k 项的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49742972/