Sorting Data
Sorting Data
Sorting Data
Sorting data in a collection
• we are already partly familiar with sort() method
• if elements in the collection are primitives, they are sorted by natural order
• if elements are Strings, then numbers sort before letters, and uppercase letters
sort before lowercase letters
2. if the current object is smaller than the argument it returns a negative number
3. if the current object is larger than the argument it returns a positive number
this.name = name;
this.age = age;
@Override
}
public class Main {
);
Collections.sort(people);
System.out.println(people);
} sorted by age
this.name = name;
this.age = age;
@Override
}
public class Main {
);
Collections.sort(people);
System.out.println(people);
} sorted by name
this.name = name;
this.age = age;
// toString() implementation
}
public class Main {
);
);
// to sort by name
Comparator<Person> c = Comparator.comparing(Person::getName);
Comparator<Person> c = Comparator.comparing(Person::getName).reversed();
// to sort by name and then by age (if names are the same)
Comparator<Person> c =
Comparator.comparing(Person::getName).thenComparingInt(Person::getAge);
Comparable vs. Comparator Summary
Comparable Comparator