Java8新特性,排序语法。
public class Human {
private String name;
private int age;
public Human() {
super();
}
public Human(final String name, final int age) {
super();
this.name = name;
this.age = age;
}
public static int compareByNameThenAge(Human lhs, Human rhs) {
if (lhs.name.equals(rhs.name)) {
return lhs.age - rhs.age;
} else {
return lhs.name.compareTo(rhs.name);
}
}
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;
}
@Override
public String toString() {
return "Human [name=" + name + ", age=" + age + "]";
}
}
Junit
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class HumanTest {
private List<Human> list;
@Before
public void setUp() throws Exception {
list = new ArrayList<>();
list.add(new Human("Eric", 23));
list.add(new Human("Joy", 45));
list.add(new Human("Evan", 63));
list.add(new Human("Ada", 29));
list.add(new Human("Bom", 33));
list.add(new Human("Jeff", 102));
list.add(new Human("Eric", 4));
System.out.println(list);
}
@After
public void tearDown() throws Exception {
System.out.println(list);
}
@Test
public void test() {
// 不使用Lambda表达式的基本排序
list.sort(new Comparator<Human>() {
@Override
public int compare(Human o1, Human o2) {
return o1.getName().compareTo(o2.getName());
}
});
}
@Test
public void test1() {
// 使用Lambda表达式的基本排序
list.sort((Human o1, Human o2) -> o1.getName().compareTo(o2.getName()));
}
@Test
public void test2() {
// 没有类型定义( Type Definitions)的基本排序
list.sort((o1, o2) -> o1.getName().compareTo(o2.getName()));
}
@Test
public void test3() {
// 使用静态方法的引用来排序
list.sort(Human::compareByNameThenAge);
}
@Test
public void test4() {
// 提取Comparator进行排序
Collections.sort(list, Comparator.comparing(Human::getName));
}
@Test
public void test5() {
// 反转排序
Comparator<Human> comparator = (h1, h2) -> h1.getName().compareTo(h2.getName());
list.sort(comparator.reversed());
}
@Test
public void test6() {
// 多条件排序
list.sort((l, r) -> {
if (l.getName().equals(r.getName())) {
return l.getAge() - r.getAge();
} else {
return l.getName().compareTo(r.getName());
}
});
}
@Test
public void test7() {
// 多条件组合排序
list.sort(Comparator.comparing(Human::getName).thenComparing(Human::getAge));
}
}