This is some notes written by Sheldon. I mainly focused on iOS programming but I also do JAVA and C# backend, you can find me with #iOSBySheldon in Github, Youtube, Facebook, etc.
High order functions with lambda
is very easy in Swift
(see article Here) but not that easy in languages like Objective-C
or C++
. In JAVA
we can do it but since JAVA
has too many versions, there are a lot different ways to do it, and there is always a better one you can choose.
Assuming we have a class like:
class Student {
private int age;
private String name;
public Student(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
}
And we will have an list of Student
to sort:
List<Student> list = new ArrayList<Student>();
list.add(new Student(33, "A"));
list.add(new Student(11, "C"));
list.add(new Student(22, "B"));
Comparator
is the most classic one but also the one with the longest typing, basically we need to create a new Comparator for our sorting.
We can use Class function of Collection
to sort:
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getAge().compareTo(o2.getAge());
}
});
Or directly use list instance function to sort:
list.sort(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o2.getAge() - o1.getAge();
}
});
Lambda
is a better and more concise way to replace Comparator for developers. (Similar in Swift
)
//lambda
list.sort((Student o1, Student o2)->o1.getName().compareTo(o2.getName()));
//lambda
list.sort((o1, o2)->o1.getAge().compareTo(o2.getAge()));
Note that for the first two ways, we are still comparing two things, but we can avoid comparing with:
list.sort(Comparator.comparing(o -> o.getName()));
Of course these are all sorting in the ascending order, if you need more complex condition to sort check the official document from Oracle Here.
This is some notes written by Sheldon. I mainly focused on iOS programming but I also do JAVA and C# backend, you can find me with #iOSBySheldon in Github, Youtube, Facebook, etc.
With a method reference instead:
list.sort(Comparator.comparing(Student::getName));
.