Find the kth smallest Contacts from a list of Contacts
Use PriorityQueue
class Contact implements Comparable< Contact>{
int age;
public Contact(int age){
this.age = age;
}
public int compareTo(Contact c){
// ordering: 1, 2, 3
return age - c.age;
}
}
public static List< Contact> findKSmallestItem(List< Contact> list, int k){
List< Contact> ret = new ArrayList<>();
PriorityQueue queue = new PriorityQueue();
for(Contact c : list){
queue.add(c);
}
while(k > 0){
Contact c = (Contact)queue.remove();
ret.add(c);
k--;
}
return ret;
}
PriorityQueue Uses Lambda in Java
class Person{
Integer age;
public Person(Integer age){
this.age = age;
}
}
PiorityQueue Queue = new PiorityQueue<>((a, b) -> a.age - b.age);
queue.add(new Person(1));
queue.add(new Person(2));
queue.add(new Person(0));
while(0 < queue.size()){
Person pe = queue.remove();
p(pe.age);
}