java.util.Comparator
package test;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
/**
* 测试Java8 lambda 函数的应用:java.util.Comparator,
* Comparator的静态方法comparing()很好用,不用构建Comparator的匿名内部类
*
* @author ray.sun
*
*/
public class ComparatorTest {
private List<Student> students;
@Before
public void setUp() {
students = Arrays.asList(
new Student("小明", 10, 130),
new Student("小军", 9, 125),
new Student("小红", 10, 132),
new Student("小飞", 8, 115),
new Student("小雨", 12, 140));
}
@Test
public void 根据年龄排序() {
students.sort(Comparator.comparing(Student::getAge));
print();
}
/*
* 默认是升序
*/
@Test
public void 根据年龄降序排序(){
students.sort(Comparator.comparing(Student::getAge, (a1, a2) -> Integer.compare(a2, a1)));
print();
}
private void print(){
System.out.println(students);
}
/*
* 构建一个学生类来测试排序
*/
class Student {
private String name;
private int age;
private double height;
public Student() {
}
public Student(String name, int age, double height) {
this.name = name;
this.age = age;
this.height = height;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
@Override
public String toString() {
return "name=" + name + ", age=" + age + ", height=" + height + "] \n";
}
}
}