Created
November 13, 2019 14:28
-
-
Save DFreds/17db0c3f8165839b7202a8ce63e5e7df to your computer and use it in GitHub Desktop.
Sorting in Dart by Comparable
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
| void main() { | |
| List<Person> list = [ | |
| Person(name: "Peter", age: 25), | |
| Person(name: "Peter", age: 22), | |
| Person(name: "John", age: 26), | |
| Person(name: "Max", age: 26) | |
| ]; | |
| print("Unsorted: $list"); | |
| list.sort((Person personA, Person personB) => personA.compareTo(personB)); | |
| print("Sorted: $list"); | |
| } | |
| class Person implements Comparable<Person> { | |
| final String name; | |
| final int age; | |
| Person({this.name, this.age}); | |
| @override | |
| String toString() { | |
| return "Name: $name - $age"; | |
| } | |
| @override | |
| int compareTo(Person other) { | |
| if (this.name.compareTo(other.name) == -1) { | |
| return -1; | |
| } | |
| if (this.name.compareTo(other.name) == 0) { | |
| if (this.age < other.age) return -1; | |
| else if (this.age == other.age) return 0; | |
| else return 1; | |
| } | |
| return 1; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment