I am trying to find the fastest and most efficient way to get the first top K items in arrayList of objects based on a custom compareable implementation.
during my research some suggested that i should use Max/Min heap which is abstracted in java as PriorityQueue. However, the problem is I dont know how to implement that on an arrayList of objects
here is my Object instance
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...
}
i want to get the first top k items based on the price. I have written a method (see below) which takes the arrayList and K (get first K items) and used StreamAPI but i know it is not the most efficient way to do it because this will sort the whole list even though I want only the first K items. so instead of having an O(n) i want have 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());
}
Any Help Please?