Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class SortLexicographicOrder {
- public static void main(String[] args) {
- Person[] people = {
- new Person("C", "F", 30),
- new Person("B", "M", 40),
- new Person("D", "M", 20),
- new Person("B", "F", 40),
- new Person("A", "F", 20)
- };
- if (true) {
- // Java8
- Arrays.sort(people,
- Comparator.comparingInt(Person::getAge)
- .thenComparing(Person::getName)
- .thenComparing(Person::getGender));
- } else {
- // Java7
- Arrays.sort(people,
- new Comparator<Person>() {
- @Override
- public int compare(Person o1, Person o2) {
- int ret;
- ret = Integer.compare(o1.getAge(), o2.getAge());
- if (ret != 0)
- return ret;
- ret = o1.getName().compareTo(o2.getName());
- if (ret != 0)
- return ret;
- return o1.getGender().compareTo(o2.getGender());
- }
- });
- }
- for (Person e : people)
- System.out.println(e);
- }
- }
- class Person {
- private final String name;
- private final String gender;
- private final int age;
- public Person(String n, String g, int a) {
- name = n;
- gender = g;
- age = a;
- }
- public String getName() { return name; }
- public String getGender() { return gender; }
- public int getAge() { return age; }
- public String toString() {
- return "{"+name+","+gender+","+age+"}";
- }
- }
Add Comment
Please, Sign In to add comment