Java8 的 Comparator 用法

java1.8 的新的函数式的 Comparator 不要太方便了. 可以轻松的实现各种List 的排序, 比以前写什么匿名的内部类, 静态类方便了很多, 很多.

 

//比较器
//按照sort_id 的升序排
//写法1
Comparator c = (a, b) -> a.getSort_id().compareTo(b.getSort_id());
//写法2
Comparator c2=Comparator.comparing(ApplyedPersonVO::getSort_id);
//写法3
Comparator c3=Comparator.comparing(a->a.getSort_id());
	
	
//默认是升序
Collections.sort(coniditionVOS, Comparator.comparing(ApprovalPersonVO.ConiditionVO::getCondtion_value));

//加上reversed()就是降序了
 Collections.sort(coniditionVOS, Comparator.comparing(ApprovalPersonVO.ConiditionVO::getCondtion_value).reversed());


//演示的示例
 //升序
List list = Arrays.asList(1, 4, 2, 6, 2, 8);
list.sort(Comparator.naturalOrder());

//降序
List list = Arrays.asList(1, 4, 2, 6, 2, 8);
list.sort(Comparator.reverseOrder());



List list = new ArrayList<>();
list.add(new Computer("xiaomi",4000,6));
list.add(new Computer("sony",5000,4));
list.add(new Computer("dell",4000,5));
list.add(new Computer("mac",6000,8));
 list.add(new Computer("micro",5000,6));
// 先以价格(升序)、后再速度(升序)
list.sort(Comparator.comparingInt(Computer::getPrice).thenComparingInt(Computer::getSpeed));
// 先以速度(降序)、后再价格(升序)
list.sort(Comparator.comparingInt(Computer::getSpeed).reversed().thenComparingInt(Computer::getPrice));
// 先以价格(降序)、后再速度(降序)
list.sort(Comparator.comparingInt(Computer::getPrice).thenComparingInt(Computer::getSpeed).reversed());

@Data
public static class Computer {
        private String name;
        private Integer price;
        private Integer speed;		
}

源码是:

import java.util.Comparator;

public class Demo {

    public static void main(String[] args) {
        Comparator c = Comparator.comparing(TimetableInfo::getTotalTime);

    }

}

编译之后是:

Java8 的 Comparator 用法_第1张图片

你可能感兴趣的:(Java,Basic)