Java的8的推出流和有用的静态 / 默认的方法比较接口可以很容易地根据个人的领域两个对象比较“值,而不需要实现一个比较(T,T)在其对象的类方法被比较。

我将使用一个简单的Song类来帮助演示这一点,接下来显示其Song.java代码清单。

Song.java

package dustin.examples.jdk8;/*** Simple class encapsulating details related to a song* and intended to be used for demonstration of JDK 8.*/
public class Song
{/** Song title. */private final String title;/** Album on which song was originally included. */private final String album;/** Song's artist. */private final String artist;/** Year song was released. */private final int year;/*** Constructor accepting this instance's title, artist, and release year.** @param newTitle Title of song.* @param newAlbum Album on which song was originally included.* @param newArtist Artist behind this song.* @param newYear Year song was released.*/public Song(final String newTitle, final String newAlbum,final String newArtist, final int newYear){title = newTitle;album = newAlbum;artist = newArtist;year = newYear;}public String getTitle(){return title;}public String getAlbum(){return album;}public String getArtist(){return artist;}public int getYear(){return year;}@Overridepublic String toString(){return "'" + title + "' (" + year + ") from '" + album + "' by " + artist;}
}

刚刚显示了清单的Song类缺少一个compare方法,但是我们仍然可以很容易地在JDK 8中比较该类的实例。 根据刚刚显示的Song的类定义,以下代码可用于根据歌曲发行年份,歌手和专辑的顺序对歌曲实例List进行排序。

按年份,艺术家和专辑对歌曲排序(按此顺序)

/*** Returns a sorted version of the provided List of Songs that is* sorted first by year of song's release, then sorted by artist,* and then sorted by album.** @param songsToSort Songs to be sorted.* @return Songs sorted, in this order, by year, artist, and album.*/
private static List<Song> sortedSongsByYearArtistAlbum(final List<Song> songsToSort)
{return songsToSort.stream().sorted(Comparator.comparingInt(Song::getYear).thenComparing(Song::getArtist).thenComparing(Song::getAlbum)).collect(Collectors.toList());
}

如果我静态地导入 ComparatorCollectors ,则上面的代码清单将稍微冗长一些,但是将这些接口和类名称包括在清单中仍然很简洁,对于该主题的入门博客文章可能更有用。

在上面的代码清单中, static default方法Comparator.comparingInt和Comparator.thenComparing用于按年份,然后是艺术家,最后是唱片,对与基础List关联的Song流进行排序。 该代码具有很高的可读性,并且可以基于任意单独的访问器方法进行对象比较(以及对这些实例进行排序),而无需显式指定的Comparator (用于每个比较的访问器结果的自然排序顺序)。 请注意,如果需要显式Comparator ,则可以通过接受Comparator的同名重载方法将其提供给这些static default方法。

下一个代码清单是整个演示类。 它包括刚刚显示的方法,还显示了由未排序的歌曲List构成的人为示例。

FineGrainSortingDemo.java

package dustin.examples.jdk8;import static java.lang.System.out;import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;/*** Demonstration of easy fine-grained sorting in JDK 8 via* stream support for sorting and Comparator's static and* default method implementations.*/
public class FineGrainSortingDemo
{/*** Construct List of {@code Song}s.* * @return Instances of {@code Song}.*/private static List<Song> generateSongs(){final ArrayList<Song> songs = new ArrayList<>();songs.add(new Song("Photograph","Pyromania","Def Leppard",1983));songs.add(new Song("Hysteria","Hysteria","Def Leppard",1987));songs.add(new Song("Shout","Songs from the Big Chair","Tears for Fears",1984));songs.add(new Song("Everybody Wants to Rule the World","Songs from the Big Chair","Tears for Fears",1985));songs.add(new Song("Head Over Heels","Songs from the Big Chair","Tears for Fears",1985));songs.add(new Song("Enter Sandman","Metallica","Metallica",1991));songs.add(new Song("Money for Nothing","Brothers in Arms","Dire Straits",1985));songs.add(new Song("Don't You (Forget About Me)","A Brass Band in African Chimes","Simple Minds",1985));return songs;}/*** Returns a sorted version of the provided List of Songs that is* sorted first by year of song's release, then sorted by artist,* and then sorted by album.** @param songsToSort Songs to be sorted.* @return Songs sorted, in this order, by year, artist, and album.*/private static List<Song> sortedSongsByYearArtistAlbum(final List<Song> songsToSort){return songsToSort.stream().sorted(Comparator.comparingInt(Song::getYear).thenComparing(Song::getArtist).thenComparing(Song::getAlbum)).collect(Collectors.toList());}/*** Demonstrate fine-grained sorting in JDK 8.** @param arguments Command-line arguments; none expected.*/public static void main(final String[] arguments){final List<Song> songs = generateSongs();final List<Song> sortedSongs = sortedSongsByYearArtistAlbum(songs);out.println("Original Songs:");songs.stream().forEach(song -> out.println("\t" + song));out.println("Sorted Songs");sortedSongs.forEach(song -> out.println("\t" + song));}
}

接下来显示运行上述代码的输出,并在使用排序代码后列出新排序的Song 。 值得注意的是,此stream.sorted()操作不会更改原始List (它作用于流而不是List )。

Original Songs:'Photograph' (1983) from 'Pyromania' by Def Leppard'Hysteria' (1987) from 'Hysteria' by Def Leppard'Shout' (1984) from 'Songs from the Big Chair' by Tears for Fears'Everybody Wants to Rule the World' (1985) from 'Songs from the Big Chair' by Tears for Fears'Head Over Heels' (1985) from 'Songs from the Big Chair' by Tears for Fears'Enter Sandman' (1991) from 'Metallica' by Metallica'Money for Nothing' (1985) from 'Brothers in Arms' by Dire Straits'Don't You (Forget About Me)' (1985) from 'A Brass Band in African Chimes' by Simple Minds
Sorted Songs'Photograph' (1983) from 'Pyromania' by Def Leppard'Shout' (1984) from 'Songs from the Big Chair' by Tears for Fears'Money for Nothing' (1985) from 'Brothers in Arms' by Dire Straits'Don't You (Forget About Me)' (1985) from 'A Brass Band in African Chimes' by Simple Minds'Everybody Wants to Rule the World' (1985) from 'Songs from the Big Chair' by Tears for Fears'Head Over Heels' (1985) from 'Songs from the Big Chair' by Tears for Fears'Hysteria' (1987) from 'Hysteria' by Def Leppard'Enter Sandman' (1991) from 'Metallica' by Metallica

JDK 8在接口中引入了流以及默认方法和静态方法(在这种情况下,尤其是在Comparator上),可以轻松地按期望的顺序逐个字段地比较两个对象,而无需使用任何显式的Comparator而是预先构建了static default方法。 Comparator界面(如果要比较的字段具有所需的自然顺序)。

翻译自: https://www.javacodegeeks.com/2018/01/easy-fine-grained-sorting-jdk-8.html

使用JDK 8轻松进行细粒度排序相关推荐

  1. jdk 细粒度锁_使用JDK 8轻松进行细粒度排序

    jdk 细粒度锁 Java的8的推出流和有用的静态 / 默认的方法比较接口可以很容易地根据个人的领域两个对象比较"值,而不需要实现一个比较(T,T)在其对象的类方法被比较. 我将使用一个简单 ...

  2. 冒泡排序实现与性能优化及JDK排序类分享

    开心一笑 [我现在出门都得带口罩,要不然就嗓子疼还咳嗽,想吸一口新鲜空气真的是太难了,估计以后纯净的空气得比红酒还值钱啊.那些有钱人出门都得背个空气瓶,见面就问:哎呦,王总啊,你的是几几年的空气啊?王 ...

  3. JDK 7的算法和数据结构

    在定期检查JDK中是否存在一种或另一种标准算法时,我决定进行这种索引. 有趣的是,为什么其中包含一些著名的数据结构或算法,而另一些却没有? 此调查的格式仅涉及JDK的算法和数据结构的关键特性和功能,所 ...

  4. 美团O2O排序解决方案——线上篇

    美团的愿景是连接消费者和商家,而搜索在其中起着非常重要的作用.随着业务的发展,美团的商家和团购数正在飞速增长.这一背景下,搜索排序的重要性显得更加突出:排序的优化能帮助用户更便捷地找到满足其需求的商家 ...

  5. java代码排序实践

    2019独角兽企业重金招聘Python工程师标准>>> 在java应用中,由于数据量少,所以排序算法很多时候我们都在用原始的方法:例如 double t;for (int i = 0 ...

  6. 字典统计排序python123_按值对字典进行排序Python(3级Dict)

    考虑使用sorted函数.使用this作为引用.对于这种情况,必须使用一个key函数来告诉python如何比较问题中字典的两个实体.然后,sorted函数返回一个您要迭代的列表.在 例如>> ...

  7. python3.6字典有序_Python如何按值对字典进行排序?

    我有一个从数据库中的两个字段中读取值的字典:一个字符串字段和一个数字字段.字符串字段是唯一的,所以这是字典的关键. 我可以对键进行排序,但是如何根据这些值进行排序? 注意:我已阅读Stack Over ...

  8. Golang sort 排序

    1.前言 开发过程中,我们经常需要对元素进行排序,使用 Go 我们可以轻松实现. Go 内置 sort 包中提供了根据一些排序函数可对任何序列进行排序,并提供自定义排序规则的能力. sort 包实现了 ...

  9. 美团搜索排序设计方案

    一.线上篇随着业务的发展,美团的商家和团购数正在飞速增长.这一背景下,搜索排序的重要性显得更加突出:排序的优化能帮助用户更便捷地找到满足其需求的商家和团购,改进用户体验,提升转化效果. 和传统网页搜索 ...

最新文章

  1. 【运维】Linux 系统 之 SSH
  2. telnet WIN7 不回显的解决办法
  3. intellij中运行后出现Hadoop is not in the classpath/dependencies
  4. 自定义 ocelot 中间件输出自定义错误信息
  5. GraphQL:验证与授权
  6. 【VMCloud云平台】SCVMM配置(四)创建模板机准备
  7. java洗扑克牌算法分析_IT兄弟连 Java语法教程 综合案例
  8. Tkinter打开一个新窗口后关闭前面的窗口
  9. 人工智能究竟能否实现?
  10. mysql手册02_事务
  11. Python数据库编程之pymysql详解
  12. 莱维特LEWITT声卡驱动安装设置方法
  13. c++编程迷宫小游戏
  14. [Maven]讲讲它的构建生命周期和拉取 jar 包流程
  15. 老男孩教育运维班100台规模集群全网数据备份项目上机实战
  16. 今天又接到了交通罚单
  17. LeetCode 2135. 统计追加字母可以获得的单词数
  18. 兆骑科创高层次人才引进双创平台,双创服务,赛事路演
  19. MYSQL计算日期差和时间差的函数
  20. java 向下转型运行时错误_8.5.2 向下转型与运行类型异常

热门文章

  1. 分表分库时机选择及策略
  2. 接口 DataInput
  3. 优秀学生专栏——孙振涛
  4. Photoshop的基本操作
  5. php公告滚动源码,10行js代码实现上下滚动公告效果方法
  6. vpn mysql_MYSQL数据库
  7. pre1-flink理论-批处理与流处理+简单示例
  8. 数据库编程——JDBC 配置
  9. 高特权级代码段转向低特权级代码段(利用 ret(retf) 指令实现 jmp from ring0 to ring3)
  10. Spring websocket 使用@Autowired 出现null