java8 lambda实现排序初探

使用它来编写Comparator和对集合(Collection)进行排序。
废话不多说上代码:

// 排序测试 供学习
    public static void main(String[] args) {
        List humans = Lists.newArrayList(new Human("Sarah", 17), new Human("Jack", 12),new Human("kevin", 20),new Human("wangkai", 28));
        // 方法一 
        humans.sort((Human h1, Human h2) -> h2.getAge() - h1.getAge());
        humans.sort((h1, h2) -> h2.getAge() - h1.getAge());
        //[ContentPageService.Human(name=wangkai, age=28), ContentPageService.Human(name=kevin, age=20), ContentPageService.Human(name=Sarah, age=17), ContentPageService.Human(name=Jack, age=12)]
        // 方法二
        Collections.sort(humans, new Comparator() {

            @Override
            public int compare(Human o1, Human o2) {
                return o2.getAge() - o1.getAge();
            }
        });
        
        // 方法三  默认升序 再反转操作 降序
        Collections.sort(humans, Comparator.comparing(Human::getAge).reversed());
        // 方式四  多条件组合排序
        humans.sort(Comparator.comparing(Human::getName).thenComparing(Human::getAge));
        System.out.println(humans);
        
    }
    
    public static int compareLikeCount(ExpertAnswer e1, ExpertAnswer e2){
        return e2.getLikeCount() - e1.getLikeCount();
    }
    
    @Data // lombok 自动生成getter setter 
    static 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;
        }
     
        
    }

喜欢这样的语法糖么,have a try !(o^^o)

你可能感兴趣的:(java8,lambda)