着重基础之—Java 8 Comparator: How to Sort a List (List排序)
首先申明,这篇博客的内容不是我自己的知识,我是从国外网站搬来的,原因有二:1是因为大天朝对网络的封锁,想用google搜点技术知识,得先FQ。2.百度上的知识点你如果仔细琢磨的话会发现,所有的搜到的知识分俩类,一类是安装教程,一类是...。
Java List排序是我们日常工作中用的比较频繁的,下面内容将介绍Java 8 Comparator 的用法:
1.字符串List 按字母顺序排列
Listcities = Arrays.asList( "Milan", "london", "San Francisco", "Tokyo", "New Delhi");System.out.println(cities);//[Milan, london, San Francisco, Tokyo, New Delhi]cities.sort(String.CASE_INSENSITIVE_ORDER);System.out.println(cities);//[london, Milan, New Delhi, San Francisco, Tokyo]cities.sort(Comparator.naturalOrder());System.out.println(cities);//[Milan, New Delhi, San Francisco, Tokyo, london]
* 这里要注意 london 小写'l'在排序过程中的细节。
2.整型数组排序
Listnumbers = Arrays.asList(6, 2, 1, 4, 9);System.out.println(numbers); //[6, 2, 1, 4, 9]numbers.sort(Comparator.naturalOrder());System.out.println(numbers); //[1, 2, 4, 6, 9]
3.根据字符串字段排序
Listmovies = Arrays.asList( new Movie("Lord of the rings"), new Movie("Back to the future"), new Movie("Carlito's way"), new Movie("Pulp fiction"));movies.sort(Comparator.comparing(Movie::getTitle));movies.forEach(System.out::println);
输出将会是:
Movie{title='Back to the future'}Movie{title='Carlito's way'}Movie{title='Lord of the rings'}Movie{title='Pulp fiction'}
4.根据Double字段排序
Listmovies = Arrays.asList( new Movie("Lord of the rings", 8.8), new Movie("Back to the future", 8.5), new Movie("Carlito's way", 7.9), new Movie("Pulp fiction", 8.9));movies.sort(Comparator.comparingDouble(Movie::getRating) .reversed());movies.forEach(System.out::println);
5.自定义排序
Listmovies = Arrays.asList( new Movie("Lord of the rings", 8.8, true), new Movie("Back to the future", 8.5, false), new Movie("Carlito's way", 7.9, true), new Movie("Pulp fiction", 8.9, false));movies.sort(new Comparator () { @Override public int compare(Movie m1, Movie m2) { if(m1.getStarred() == m2.getStarred()){ return 0; } return m1.getStarred() ? -1 : 1; }});movies.forEach(System.out::println);
输出将会是:
Movie{starred=true, title='Lord of the rings', rating=8.8}Movie{starred=true, title='Carlito's way', rating=7.9}Movie{starred=false, title='Back to the future', rating=8.5}Movie{starred=false, title='Pulp fiction', rating=8.9}
当然,我们也可以用lambda表达式代替匿名类,如下:
movies.sort((m1, m2) -> { if(m1.getStarred() == m2.getStarred()){ return 0; } return m1.getStarred() ? -1 : 1;});
6.链式表达式排序
Listmovies = Arrays.asList( new Movie("Lord of the rings", 8.8, true), new Movie("Back to the future", 8.5, false), new Movie("Carlito's way", 7.9, true), new Movie("Pulp fiction", 8.9, false));movies.sort(Comparator.comparing(Movie::getStarred) .reversed() .thenComparing(Comparator.comparing(Movie::getRating) .reversed()));movies.forEach(System.out::println);
输出结果如下:
Movie{starred=true, title='Lord of the rings', rating=8.8}Movie{starred=true, title='Carlito's way', rating=7.9}Movie{starred=false, title='Pulp fiction', rating=8.9}Movie{starred=false, title='Back to the future', rating=8.5}
好了,就转载到这里。