簡體   English   中英

如何使用列表在地圖中分組時過濾年齡

[英]How to filter the age while grouping in map with list

類似我剛才的問題在這里 ,我有用戶對象是這些

new User("ayush","admin",23)
new User("ashish","guest",19) 
new User("ashish","admin",20) 
new User("garima","guest",29)
new User("garima","super",45)
new User("garima","guest",19)

現在我試圖讓這些用戶知道不同年齡段的名稱。 但我需要將它們過濾到threshold年齡以上。 我可以使用這個趨勢

Map<String, List<Integer>> userNameAndAgeTrend = users.stream().collect(Collectors.groupingBy(user-> user.getName(), Collectors.mapping(u-> u.getAge(), toList())));

這給了我{ashish=[19, 20], garima=[29, 45, 19], ayush=[23]} 但是在我使用這種分組的情況下,我無法使用閾值正確過濾列表,例如21年 有人可以幫忙嗎?

另外,使用.filter(user -> user.getAge() > 21)沒有為ashish提供映射,這也是我想要存儲的。 我可以在我的機器上安裝Java10並嘗試建議的解決方案。

Stream.filter

您可以使用filter作為

Map<String, List<Integer>> userNameAndAgeTrend = users.stream()
        .filter(a -> a.getAge() > 21) // only above 21
        .collect(Collectors.groupingBy(User::getName, Collectors.mapping(User::getAge, Collectors.toList())));

正如您在評論中所證實的那樣,這將為您提供輸出

 {garima=[29, 45], ayush=[23]} 

Collectors.filtering

如果你正在尋找所有的名字,你也可以使用Collectors.filtering因為明確地調用了類似的行為(格式化我的):

使用如上所示的filtering收集器將導致從該部門到空集的映射

如果改為執行了流filter()操作, 那么該部門根本就沒有映射

它的用法應該類似於:

Map<String, List<Integer>> userNameAndAgeTrend = users.stream()
        .collect(Collectors.groupingBy(User::getName, Collectors.mapping(User::getAge, 
                        Collectors.filtering(age -> age > 21, Collectors.toList()))));

現在的輸出就是

 {ashish=[], garima=[29, 45], ayush=[23]} 

如果要分組進行filter

users.stream()
     .filter(u -> u.getAge() > 21) //<--- apply the filter operation
     ...

filter是一個中間操作,它使人們能夠“保持滿足所提供謂詞的元素”並排除其他不支持的元素。

因此,在filter操作之后,您有一個新流,該流僅包含傳遞提供的謂詞的元素。 在這種情況下,只有年齡超過21歲的用戶。


如果你想分組 filter (不要與流中的filter混淆,這有點不同)

從JDK9開始的filtering收集器:

users.stream()
     .collect(groupingBy(User::getName, 
            filtering(u -> u.getAge() > 21, 
                   mapping(User::getAge, toList()))));

看,接受的答案在這里的JDK8實現。

使用上面的流filter ,首先過濾值,然后將其分組。 換句話說,在過濾后我們對它們“沒有痕跡”。

但是,使用JDK9filtering收集器,我們可以保持跟蹤。

您需要添加.filter()在手術前.collect()一個

Map<String, List<Integer>> userNameAndAgeTrend = 
                      users.stream()
                           .filter(user -> user.getAge() > 21)
                           .collect(Collectors.groupingBy(user-> user.getName(), Collectors.mapping(u-> u.getAge(), toList())));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM