亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 Java 8 按兩個字段對對象進行分組

使用 Java 8 按兩個字段對對象進行分組

繁花不似錦 2022-05-12 15:04:45
我在使用 Java 8 對兩個值進行分組時遇到問題。我的主要問題是對兩個字段進行分組,我正確地將一個字段分組,getNameOfCountryOrRegion()但現在我對groupingBy另一個也被調用leagueDTO的字段感興趣。Map<String, List<FullCalendarDTO>> result = countryDTOList.stream()               .collect(Collectors.groupingBy(                             FullCalendarDTO::getNameOfCountryOrRegion));以及以下課程:public class FullCalendarDTO  {    private long id;    private TeamDTO localTeam;    private TeamDTO visitorTeam;    private LocationDTO location;       private String leagueDTO;           private String timeStamp;    private String nameOfCountryOrRegion;}結果將按 和nameOfCountryOrRegion分組leagueDTO。
查看完整描述

3 回答

?
猛跑小豬

TA貢獻1858條經驗 獲得超8個贊

downstream將收集器傳遞給groupingBy將起到作用:

countryDTOList.stream()
              .collect(groupingBy(FullCalendarDTO::getNameOfCountryOrRegion,
                       groupingBy(FullCalendarDTO::getLeagueDTO)));

上面的代碼片段會將您的FullCalendarDTO對象nameOfCountryOrRegion分組,然后每個組將按leagueDTO.

所以返回的集合看起來像Map<String, Map<String, List<FullCalendarDTO>>>.


查看完整回答
反對 回復 2022-05-12
?
青春有我

TA貢獻1784條經驗 獲得超8個贊

如果您要使用兩個屬性進行分組,您的輸出將是 a Map,其中鍵作為用于分組getNameOfCountryOrRegion) 的第一個屬性,值作為 aMap再次使用鍵作為用于分組getLeagueDTO) 的第二個屬性,其值作為 aList<FullCalendarDTO>進行分組基于指定的鍵。

這應該看起來像:

Map<String, Map<String, List<FullCalendarDTO>>> result = countryDTOList.stream()
        .collect(Collectors.groupingBy(FullCalendarDTO::getNameOfCountryOrRegion,
                Collectors.groupingBy(FullCalendarDTO::getLeagueDTO)));


查看完整回答
反對 回復 2022-05-12
?
LEATH

TA貢獻1936條經驗 獲得超7個贊

Collectors 類 groupingBy() 方法支持額外的 Collector 作為第二個參數:

public static <T, K, A, D>    Collector<T, ?, Map<K, D>> groupingBy(Function<? super T, ? extends K> classifier,Collector<? super T, A, D> downstream)

上面可以寫成 groupBy() 兩個值

Map<String, List<FullCalendarDTO>> result = countryDTOList.stream().collect(Collectors.groupingBy(FullCalendarDTO::getNameOfCountryOrRegion, Collectors.groupingBy(FullCalendarDTO::getLeagueDTO)));



查看完整回答
反對 回復 2022-05-12
  • 3 回答
  • 0 關注
  • 1865 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號