2017-07-18 64 views
-1

因此,我有一個任務使用Comparator對lambertda進行排序,並使用lambda和stream方法,之後我必須比較排序列表所需的時間比較器與lambda和流組合。如何使用lambda和流方法對列表進行排序

比方說,我有一個Communication類有commTimeClient屬性(在ClientgetSurname方法)。 現在,在應用程序中,我必須使用上述兩種方法對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); 

,但我不知道我能做些什麼。

對於我必須確定排序長度的應用程序部分,我知道如何去做,所以不需要解釋那部分(至少我知道怎麼做,對嗎?)。

+0

這是一個從這個問題正是你被卡住不清楚。你是否收到你不明白的錯誤?不正確的結果?其他一些問題? –

+0

'communications.stream()。sorted(byTimeAndSurname)'不會做任何事情,因爲**沒有終端操作**。你最後需要像'.collection(Collectors.toList())'這樣的東西,然後把它分配給一個變量。 – Andreas

回答

1

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); 
相關問題