comparable VS comparator
comparable 给了要比较的list internal的能力,而comparator给了external的能力。这句话听起来比较抽象,但是很好理解。comparator是要另外写一个类,并且将这个类传入。
这里需要引入一个性质JAVA8:functional interface
- exactly only one abstract method
- may have many dafault and static method
static method doesn’t belong to instance
- extends java.util.function.Function
- java.lang.comparable is not a functional interface
lamada expression
package java_learning.Interface;
//package java_learning.Interface;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/** list all the knowledge point
* 1. Comparable VS comparator
* 1.1 comparable: in this case, we need to implement comparable on the "People", so that we can use Collections.sort(people_list);
* 2.2 comparator: define another class, so that we can use it
* 2. lamada expression
* 3. a.age < b.age ? -1 : a.age == b.age ? 0 : 1;
* @author junyu
*
*/
public class test_compare {
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Joe", 24),
new Person("Pete", 18),
new Person("Chris", 21)
);
Collections.sort(people, new LexicographicComparator());// use the
System.out.println(people);
Collections.sort(people, new Comparator<Person>() {
@Override
public int compare(Person a, Person b) {
// TODO Auto-generated method stub
return a.age < b.age ? -1 : a.age == b.age ? 0 : 1;
}
});
System.out.println(people);
// people.sort((Person a, Person b)->(a.age < b.age ? -1 : a.age == b.age ? 0 : 1));
System.out.println(people);
Collections.sort(people, (Person a, Person b)->(a.age < b.age ? -1 : a.age == b.age ? 0 : 1));
System.out.println(people);
}
}
class LexicographicComparator implements Comparator<Person> {
@Override
public int compare(Person a, Person b) {
return -a.name.compareTo(b.name);
}
}
class Person{
String name;
int age;
Person(String n, int a) {
name = n;
age = a;
}
@Override
public String toString() {
return String.format("{name=%s, age=%d}", name, age);
}
}