我在使用 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>>>
.

青春有我
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)));

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)));
添加回答
舉報
0/150
提交
取消