Java8比较器-如何对List排序详解
在本文中,我们将看到几个关于如何在Java 8中对List进行排序的例子。
按字母排序字符串列表
List<String> cities = 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”使用小写字母,是为了更好地突出 Comparator.naturalOrder() (返回首先排序大写字母的比较器)和 String.CASE_INSENSITIVE_ORDER(返回不区分大小写的比较器)之间的差异。
基本上,在Java 7中,我们使用Collection.sort()接受List和最后的Comparator ——在Java 8中,我们有新的 List.sort() 用于接受Comparator。
对整数列表排序
List<Integer> numbers = 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]
按字符串字段对列表排序
假设我们有一个Movie类,并且我们要“按标题title”对List排序。我们可以使用 Comparator.comparing() ,传递一个函数,函数提取用于排序title的字段——在本例中。
List<Movie> movies = 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'}
可能你会注意到我们没有通过任何Comparator ,但正确排序了List。这是因为title——提取的字段——是一个字符串,并且字符串实现了可比较的接口。如果你看看Comparator.comparing()实现,你会看到它对提取的键调用compareTo。
return (Comparator<T> & Serializable) (c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2));
按double字段对列表排序
以类似的方式,我们可以使用 Comparator.comparingDouble()来比较double值。在示例中,我们想按最高到最低的评分来订购Movie列表。
List<Movie> movies = 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);
我们在Comparator上使用reversed函数,以便反转默认的从最低到最高的自然顺序。 Comparator.comparingDouble()在内部使用Double.compare()。
如果你需要比较int或long,那么你可以分别使用comparingInt()和comparingLong()。
使用自定义比较器对列表排序
在前面的例子中,我们没有指定任何比较器,因为没有必要,但让我们看一个例子,例子中我们定义了我们自己的比较器。我们的Movie类有一个新的字段——“starred”——使用第三个构造函数参数设置。在示例中,我们要对列表进行排序,以便列表顶部为已加星标的电影。
List<Movie> movies = 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<Movie>() { @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表达式而不是Anonymous类,如下所示:
movies.sort((m1, m2) -> { if(m1.getStarred() == m2.getStarred()){ return 0; } return m1.getStarred() ? -1 : 1; });
我们也可以再次使用Comparator.comparing():
movies.sort(Comparator.comparing(Movie::getStarred, (star1, star2) -> { if(star1 == star2){ return 0; } return star1 ? -1 : 1; }));
在最新的示例中,Comparator.comparing()将第一个参数作为提取用于排序的键的函数,并将Comparator作为第二个参数。Comparator 使用提取的键进行比较,star1和star2真是布尔值,分别表示m1.getStarred()和m2.getStarred()。
用比较链排序列表
在最后一个例子中,我们要在顶部加上已加星标的电影,然后按评分排序。
List<Movie> movies = 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}
正如你所看到的,我们首先按星标,然后按评分进行排序——两者都反转,因为我们想要最高的值和真正的第一。
以上是Java8比较器-如何对List排序详解的详细内容。更多信息请关注PHP中文网其他相关文章!

Java8计算一年前或一年后的日期利用minus()方法计算一年前的日期packagecom.shxt.demo02;importjava.time.LocalDate;importjava.time.temporal.ChronoUnit;publicclassDemo09{publicstaticvoidmain(String[]args){LocalDatetoday=LocalDate.now();LocalDatepreviousYear=today.minus(1,ChronoUni

当涉及到MicrosoftExcel时,表格最为常见。因此,每个人都非常清楚如何在MicrosoftExcel中对表格内的数据进行排序。但是当涉及到Word时,表格很少见,并且需要在Word中对表格中的数据进行排序的情况更加罕见。但可以肯定的是,您可能需要在Word文档中有一个表格,有时您甚至可能需要对其中的数据进行排序。在Word表中对数据进行排序的一种方法是将数据导入Excel,从Excel进行排序,然后将排序后的表带回Word。好吧,甚至不要考虑诉诸这种方式!当Word本身具有对表

Java8如何计算一周后的日期这个例子会计算一周后的日期。LocalDate日期不包含时间信息,它的plus()方法用来增加天、周、月,ChronoUnit类声明了这些时间单位。由于LocalDate也是不变类型,返回后一定要用变量赋值。packagecom.shxt.demo02;importjava.time.LocalDate;importjava.time.temporal.ChronoUnit;publicclassDemo08{publicstaticvoidmain(String[

Vectors实现了List接口,用于创建动态数组。大小不固定且可以根据我们的需求增长的数组被称为动态数组。Comparator是‘java.util’包中可用的一个接口。排序意味着按升序或降序重新排列给定列表或数组的元素。在本文中,我们将创建一个向量,然后尝试使用比较器按降序对其元素进行排序。按降序排列Java向量的程序Comparator正如其名称所示,它用于比较某些东西。在Java中,Comparator是一个接口,用于对自定义对象进行排序。我们可以在其内置方法“compare()”中编写

用于对Java对象进行排序的Java比较器接口。Java中的比较器类通过调用“java.util.comparator”来比较不同的对象(Obj01、Obj02)。在此方法中,可以根据返回值对对象进行比较。比较可以是正数、相等或负数。该过程为用户提供了多个排序序列。有很多方法可以对两种方法进行比较。publicintcompareclass(obj1,obj2)-执行两个对象之间的比较。publicBooleanequals(obj)-比较当前对象与指定对象。Java集合类-提供对数据集合中的元

在Java8中获取当前的时间戳Instant类有一个静态工厂方法now()会返回当前的时间戳,如下所示:packagecom.shxt.demo02;importjava.time.Instant;publicclassDemo16{publicstaticvoidmain(String[]args){Instanttimestamp=Instant.now();System.out.println("Whatisvalueofthisinstant"+timestamp.t

Java8中如何使用预定义的格式化工具去解析或格式化日期packagecom.shxt.demo02;importjava.time.LocalDate;importjava.time.format.DateTimeFormatter;publicclassDemo17{publicstaticvoidmain(String[]args){StringdayAfterTommorrow="20180205";LocalDateformatted=LocalDate.parse

Java8中获取年、月、日信息packagecom.shxt.demo02;importjava.time.LocalDate;publicclassDemo02{publicstaticvoidmain(String[]args){LocalDatetoday=LocalDate.now();intyear=today.getYear();intmonth=today.getMonthValue();intday=today.getDayOfMonth();System.out.println


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

SublimeText3汉化版
中文版,非常好用

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

Dreamweaver CS6
视觉化网页开发工具

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中