如何使用lambda和流方法对列表进行排序
因此,我有一个任务使用Comparator
对lambertda进行排序,并使用lambda和stream方法,之后我必须比较排序列表所需的时间比较器与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();
顺便说一句communications.stream().sorted(byTimeAndSurname);
各种流,而不是它的源(communications
)。如果要排序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);
或者为(丑陋)“的一行”:
Function<Communication, String> bySurname =
((Function<Communication, Client>)Communication::getClient)
.andThen(Client::getSurname);
这是一个从这个问题正是你被卡住不清楚。你是否收到你不明白的错误?不正确的结果?其他一些问题? –
'communications.stream()。sorted(byTimeAndSurname)'不会做任何事情,因为**没有终端操作**。你最后需要像'.collection(Collectors.toList())'这样的东西,然后把它分配给一个变量。 – Andreas