Comparator.comparing().thenComparing type inference problem

Ivar_PredixCN 2017-06-16 10:55:48
The problem is type inferencing. Without adding a (Song s) to the first comparison, comparator.comparing doesn't know the type of the input so it defaults to Object.
You can fix this problem 1 of 3 ways:

Use the new Java 8 method reference syntax
Collections.sort(playlist,
Comparator.comparing(Song::getTitle)
.thenComparing(Song::getDuration)
.thenComparing(Song::getArtist)
);
Pull out each comparison step into a local reference
Comparator<Song> byName = (s1, s2) -> s1.getArtist().compareTo(s2.getArtist());
Comparator<Song> byDuration = (s1, s2) -> Integer.compare(s1.getDuration(), s2.getDuration());
Collections.sort(playlist,
byName
.thenComparing(byDuration)
);
Forcing the type returned by the Comparator (note you need both the input type and the comparison key type)
sort(
Comparator.<Song, String>comparing((s) -> s.getTitle())
.thenComparing(p1 -> p1.getDuration())
.thenComparing(p1 -> p1.getArtist())
);
I think the "last" thenComparing syntax error is misleading you. It's actually a type problem with the whole chain, it's just the compiler only marking the end of the chain as a syntax error because that's when the final return type doesn't match I guess.

I'm not sure why List is doing a better inferencing job than Collection since it should do the same capture type but apparently not.
...全文
181 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

163

社区成员

发帖
与我相关
我的任务
社区描述
GE的Predix平台整合云计算可扩展性、大数据管理和高级分析技术来助力新一代的数字化企业。结合GE自己作为全球工业界领导者的经验,Predix云平台为开发高级工业应用程序提供可连接性、安全和高性能。
云计算大数据 技术论坛(原bbs)
社区管理员
  • GE Predix工业互联网开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧