Skip to content

Instantly share code, notes, and snippets.

@shailrshah
Last active September 30, 2017 02:39
Show Gist options
  • Save shailrshah/642e177497a3df1f27d479fe3a87829c to your computer and use it in GitHub Desktop.
Save shailrshah/642e177497a3df1f27d479fe3a87829c to your computer and use it in GitHub Desktop.
Sort a list of objects by a property of the class
import java.util.Comparator;
import java.util.Arrays;
class Sorting {
public static void main(String[] args) {
Person p1 = new Person("Chagan", 145, 49);
Person p2 = new Person("Lagan", 150, 49);
Person p3 = new Person("Magan", 154, 22);
Person p4 = new Person("Gagan", 155, 34);
Person[] people = new Person[]{p1, p2, p3, p4};
Arrays.sort(people, Comparator.comparing(Person::getAge).thenComparing(Person::getName).thenComparing(Person::getHeight));
for(Person person : people) {
person.print();
}
}
}
// Magan is 22 years old and is 154cms long.
// Gagan is 34 years old and is 155cms long.
// Chagan is 49 years old and is 145cms long.
// Lagan is 49 years old and is 150cms long.
class Person {
private String name;
private int height;
private int age;
Person(String name, int height, int age) {
this.name = name;
this.height = height;
this.age = age;
}
public String getName() {
return this.name;
}
public int getHeight() {
return this.height;
}
public int getAge() {
return this.age;
}
public void print() {
System.out.println(this.name + " is " + this.age + " years old and is " + this.height + "cms long.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment