Created
March 19, 2018 22:32
-
-
Save shailrshah/d5a6e570bdaaf9294be4ec03526b1707 to your computer and use it in GitHub Desktop.
Sort a list of people using CompareTo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Collections; | |
import java.util.List; | |
public class Person implements Comparable<Person>{ | |
private int age; | |
private String name; | |
Person(String name, int age) { | |
this.name = name; | |
this.age = age; | |
} | |
@Override | |
public int compareTo(Person o) { | |
int ageAsc = this.age - o.age; | |
int nameAsc = this.name.compareTo(o.name); | |
return ageAsc != 0 ? ageAsc : nameAsc; | |
} | |
@Override | |
public boolean equals(Object o) { | |
return (o instanceof Person) | |
&& ((Person)o).name.equals(this.name) | |
&& ((Person)o).age == this.age; | |
} | |
@Override | |
public int hashCode() { | |
return age; | |
} | |
public static void sort(List<Person> people) { | |
Collections.sort(people); // Person needs to implement Comparable<Person> | |
} | |
public static void sort2(List<Person> people) { | |
people.sort((p1, p2) -> { | |
int ageDesc = p2.age - p1.age; | |
int nameAsc = p1.name.compareTo(p2.name); | |
return ageDesc != 0 ? ageDesc : nameAsc; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment