# How to sort a List\ in JAVA in a better way / the best way? 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](https://gist.github.com/SheldonWangRJT/791c85749051cf4b63b1590f08143156)) 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: ```java 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: ```java List list = new ArrayList(); list.add(new Student(33, "A")); list.add(new Student(11, "C")); list.add(new Student(22, "B")); ``` Sorting with Comparator --- `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: ```java Collections.sort(list, new Comparator() { @Override public int compare(Student o1, Student o2) { return o1.getAge().compareTo(o2.getAge()); } }); ``` Or directly use list instance function to sort: ```java list.sort(new Comparator() { @Override public int compare(Student o1, Student o2) { return o2.getAge() - o1.getAge(); } }); ``` Sorting with Lambda --- `Lambda` is a better and more concise way to replace Comparator for developers. (Similar in `Swift`) ```java //lambda list.sort((Student o1, Student o2)->o1.getName().compareTo(o2.getName())); //lambda list.sort((o1, o2)->o1.getAge().compareTo(o2.getAge())); ``` Sorting with Super Lambda Comparator --- Note that for the first two ways, we are still comparing two things, but we can avoid comparing with: ```java 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](https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html). :) --- 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.