lambda表达式排序

lambda表达式排序简洁

1.给一个字符串数组:

String[] atp = {"2016-06-28 08:00:00", "2017-12-05 19:17:32","2017-03-06 22:14:51","2016-12-28 08:00:00", "2017-03-05 19:17:32","2017-03-06 22:14:51"};

打印结果如图所示:

2016-06-28 08:00:00
2017-12-05 19:17:32
2017-03-06 22:14:51
2016-12-28 08:00:00
2017-03-05 19:17:32
2017-03-06 22:14:51

2.通过lambda对数组排序:

Arrays.sort(atp, (String s1, String s2) -> (s1.compareTo(s2)));//Lambdas排序集合

打印结果:

2016-06-28 08:00:00
2016-12-28 08:00:00
2017-03-05 19:17:32
2017-03-06 22:14:51
2017-03-06 22:14:51
2017-12-05 19:17:32

3.lambda对list集合排序

定义一个对象:

    public static class People {
        private String date;

        public People(String date) {
            this.date = date;
        }

        public String getDate() {
            return date;
        }

        public void setDate(String date) {
            this.date = date;
        }

        @Override
        public String toString() {
            return "People{" +
                    "date='" + date + '\'' +
                    '}';
        }
    }

将字符串数组加到对象中,并排序:

for(String str: atp){
            list.add(new People(str));
        }
        //------------------集合排序--------------------
        //1.在java8之前,给list排序需要使用实现java.util.Comparator接口的匿名类:
        Collections.sort(
                list,
                new Comparator<People>() {
                    public int compare(People p1, People p2){
                        return p1.getDate().compareTo(p2.getDate());
                    }
                }
        );
        //2.java8开始可以使用lambda表达式替换匿名类。注意左边的参数p1、p2在编译时自动推导:
        Collections.sort(list, (p1, p2) -> p1.getDate().compareTo(p2.getDate()));
        //3.这个例子使用Comparator.comparing 和 ::双冒号可以简单表示:
        Collections.sort(list, Comparator.comparing(People::getDate));
        list.forEach(people->{
            System.out.println(people.getDate());
        });

 lambda对于map按ASCII排序:

//map排序
        Map<String, Integer> map = new HashMap();
        map.put("349",12);
        map.put("329",13);
        map.put("6",14);
        map.put("399",15);
        map.put("99",16);
        map = map.entrySet()
                .stream()
                .sorted(Map.Entry.<String, Integer>comparingByKey()) //comparingByValue  ,comparingByKey排出来的329 、6 ......
                .collect(Collectors.toMap(k -> k.getKey(), v -> v.getValue(),
                        (k, v) -> k, LinkedHashMap::new));

 ######lambda对对象属性排序:

升序:

  

List<User> newList = list.stream().sorted(Comparator.comparing(User::getAge))
                                  .collect(Collectors.toList());

降序:

  

List<User> newList = list.stream().sorted(Comparator.comparing(User::getAge).reversed())
                                  .collect(Collectors.toList());

 

posted @ 2018-10-10 23:20  何其小静  阅读(37461)  评论(0编辑  收藏  举报