Higher order function - nus-cs2030/2021-s1 GitHub Wiki
There are quite a number of ways to build higher order function. Let's take comparator as an example.
Single use class
class PersonComparator implements Comparator<Person> {
@Override
public int compare(Person a, Person b){
return a.getName().compareTo(b.getName());
}
}
PriorityQueue<Person> pq = new PriorityQueue<>(new PersonComparator());
Anonymous class
PriorityQueue<Person> pq = new PriorityQueue<>(new Comparator<Person>() {
@Override
public int compare(Person a, Person b){
return a.getName().compareTo(b.getName());
}
});
Lambda: both method reference and lambda closure works fine
Closure
PriorityQueue<Person> pq = new PriorityQueue<>((x,y) -> x.getName().compareTo(y.getName()));
Method reference: apply to any object
// pre-requisite: You need to have a getter method for that attribute that you wish to compare
PriorityQueue<Person> pq = new PriorityQueue<>(Comparator.comparing(Person::getName));
pq.add(new Person("charlie"));
pq.add(new Person("alpha"));
pq.add(new Person("delta"));
pq.add(new Person("bravo"));
while(!pq.isEmpty()) {
System.out.println(pq.poll());
}