所以我有一个任务来对某个 List
进行排序使用Comparator
并将 lambda 与流方法一起使用,之后我必须比较使用比较器与 lambda 和流组合对列表进行排序所需的时间。
假设我有一个 Communication
具有 commTime
的类和一个 Client
属性(Client
有一个 getSurname
方法)。
现在,在应用程序中,我必须对 communications
进行排序使用上述两种方法列出。我已经使用 Comparator
完成了该操作,但我在使用 lambda 和 Stream 方法时遇到问题。
我有这样的东西:
Collections.sort(communications, (comm1, comm2) -> comm1.getCommTime().compareTo(comm2.getCommTime()));
这将属于if
声明(如果时间不相等),但如果相等,我必须通过比较通信中客户的姓氏对列表进行排序。我不知道该怎么做,更准确地说 - 我不知道如何从通信本身获取客户的姓氏。
我做不到:
Function<Communication, LocalDateTime> byTime = Communication::getCommTime;
Function<Communication, String> bySurname = Communication.getClient()::getSurname;
Comparator<Communication> byTimeAndSurname = Comparator.comparing(byTime).thenComparing(bySurname);
communications.stream().sorted(byTimeAndSurname);
但我不知道我能做什么。
对于应用程序中我必须确定排序长度的部分,我知道如何做到这一点,因此无需解释该部分(至少我知道如何做某事,对吧?)。
最佳答案
Communication.getClient()::getSurname; 几乎没有问题。由于 .getClient()
不是静态的,因此您不能将其用作 Communication.getClient()
。另一个问题是,它会为一个对象创建方法引用,该对象将在创建此方法引用时从 getClient()
返回。
最简单的方法是使用 lambda 表达式,例如
Function<Communication, String> bySurname = com -> com.getClient().getSurname();
BTW communications.stream().sorted(byTimeAndSurname);
对流进行排序,而不是其源(communications
)。如果您想对通信
进行排序,您应该使用
Collections.sort(communications, byTimeAndSurname);
<小时/>
通过 A->B->C
实现 A->C
映射的其他方法是使用
someAToBFunction.andThen(someBToCFunction)
^^^^^^^
(documentation)。在你的情况下你可以写
Function<Communication, Client> byClient = Communication::getClient;
Function<Communication, String> bySurname = byClient.andThen(Client::getSurname);
或者作为(丑陋的)“one-liner”:
Function<Communication, String> bySurname =
((Function<Communication, Client>)Communication::getClient)
.andThen(Client::getSurname);
关于java - 如何使用 lambda AND 流方法对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45177448/