[英]Grouping objects by two fields using Java 8
我有一個問題,用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
分組。
將downstream
收集器傳遞給groupingBy
可以解決這個問題:
countryDTOList.stream()
.collect(groupingBy(FullCalendarDTO::getNameOfCountryOrRegion,
groupingBy(FullCalendarDTO::getLeagueDTO)));
上面的代碼片段將通過nameOfCountryOrRegion
對FullCalendarDTO
對象進行分組,然后每個組將按照leagueDTO
進行分組。
因此返回的集合看起來像Map<String, Map<String, List<FullCalendarDTO>>>
。
如果要使用兩個屬性進行分組,則輸出將是一個Map
其中鍵作為用於分組的第一個屬性 ( getNameOfCountryOrRegion
),而值又作為Map
再次使用鍵作為用於分組的第二個屬性 ( getLeagueDTO
),其值為List<FullCalendarDTO>
,它們根據指定的鍵進行分組。
這應該是這樣的:
Map<String, Map<String, List<FullCalendarDTO>>> result = countryDTOList.stream()
.collect(Collectors.groupingBy(FullCalendarDTO::getNameOfCountryOrRegion,
Collectors.groupingBy(FullCalendarDTO::getLeagueDTO)));
收集器類groupingBy()方法支持另一個收集器作為第二個參數:
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)));
如果您要查找原始列表,請將其分組到地圖地圖中。 以下是代碼段
List<FullCalendarDTO> arrayList = new ArrayList<FullCalendarDTO>();
arrayList.add(new FullCalendarDTO("US","A"));
arrayList.add(new FullCalendarDTO("EU","A"));
arrayList.add(new FullCalendarDTO("EU","A"));
arrayList.add(new FullCalendarDTO("US","A"));
arrayList.add(new FullCalendarDTO("US","B"));
Map<String, List<FullCalendarDTO>> result = arrayList.stream().collect(Collectors.groupingBy(FullCalendarDTO::getNameOfCountryOrRegion));
HashMap<String, Map<String, List<FullCalendarDTO>>> finalOutput = new HashMap<String, Map<String, List<FullCalendarDTO>>>();
for (Entry<String, List<FullCalendarDTO>> fullCalendarDTO : result.entrySet()) {
Map<String, List<FullCalendarDTO>> collect = fullCalendarDTO.getValue().stream().collect(Collectors.groupingBy(FullCalendarDTO::getLeagueDTO));
finalOutput.put(fullCalendarDTO.getKey(), collect);
}
System.out.println(finalOutput);
哪個輸出
{EU = {A = [EU :: A,EU :: A]},US = {A = [US :: A,US :: A],B = [US :: B]}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.