首页  

Java8 Lambda表达式排序实战     所属分类 java8 浏览量 958


public class SortTest {

	public static void main(String[] args) throws Exception {
		System.out.println("lambda SortTest start " + LocalDateTime.now());

		List<Pet> pets = new ArrayList<>();
		pets.add(new Pet("tiger",9));
		pets.add(new Pet("tiger",7));
		pets.add(new Pet("cat",8));
		pets.add(new Pet("cat",3));
		pets.add(new Pet("cat",5));
		
		System.out.println(pets);
		
		
		pets.sort((final Pet pet1, final Pet pet2) -> pet1.name.compareTo(pet2.name));
		System.out.println(pets);
		
		pets.sort((Pet pet1,Pet pet2) -> pet1.name.compareTo(pet2.name));
		System.out.println(pets);
		
		pets.sort((pet1,pet2) -> pet1.name.compareTo(pet2.name));
		System.out.println(pets);

		// compareByName  must be public !!!
		pets.sort(Pet::compareByName);
		System.out.println(pets);
		
		pets.sort(Pet::compareByNameDesc);
		System.out.println(pets);
		
		pets.sort(Pet::compareByAgeDesc);
		System.out.println(pets);


		pets.sort(Comparator.comparing(Pet::getName));
		System.out.println(pets);


		Comparator<Pet> comp = Pet::compareByAge;
		pets.sort(comp);
		System.out.println(pets);
		
		pets.sort(comp.reversed());
		System.out.println(pets);

		// 组合条件
		comp = Comparator.comparing(Pet::getName).thenComparing(Pet::getAge);
		pets.sort(comp);
		System.out.println(pets);
        	
	}
}






完整代码

https://gitee.com/dyyx/hellocode/blob/master/src/dyyx/java8/lambda/SortTest.java
https://gitee.com/dyyx/hellocode/blob/master/src/dyyx/java8/lambda/Pet.java


java8 Lambda 实例 lambda使用说明 lambda的优雅用法

上一篇     下一篇
Linux vmstat 命令

hashmap调优

JDK15和ZGC

java方法引用实例

Java8 Stream 及 常见坑点

java方法引用