3 回答

TA貢獻1943條經驗 獲得超7個贊
首先,您可能應該將數據加載到有意義的 DTO/POJO 中:
class Row {
String country;
String gender;
int income;
// Getters etc.
}
然后,給定 a List<Row>,您可以簡單地這樣做:
Map<String, Double> groupedByCountry = list.stream().collect(
Collectors.groupingBy(Row::getCountry,
Collectors.averagingInt(Row::getIncome)
)
Map<String, Double> groupedByGender = list.stream().collect(
Collectors.groupingBy(Row::getGender,
Collectors.averagingInt(Row::getIncome)
)
Map<String, Map<String, Double>> groupedByCountryAndGender = list.stream().collect(
Collectors.groupingBy(Row::getCountry,
Collectors.groupingBy(Row::getGender,
Collectors.averagingInt(Row::getIncome)
)
對于您給出的結構(RowData帶有RowCells 的列表):
Map<String, Map<String, Double>> groupedByCountryAndGender = list.stream().collect(
Collectors.groupingBy(r -> r.getCells().get(0).getValue(),
Collectors.groupingBy(r -> r.getCells().get(1).getValue(),
Collectors.averagingInt(r -> Integer.valueOf(r.getCells().get(2).getValue()))
)

TA貢獻1839條經驗 獲得超15個贊
創建一個更符合邏輯的數據分組,例如:
class RowData {
private String country;
private String gender;
private double income;
// constructor, getters, setters
}
數據包含在以下列表中:
List<RowData> rowDataList = Arrays.asList(new RowData("IND", "M", 23531),
new RowData("IND", "F", 2331), new RowData("IND", "M", 2331),
new RowData("SNG", "M", 22111), new RowData("HUD", "F", 20012));
現在你可以:
Map<String, Double> dataMap = rowDataList.stream()
.collect(Collectors.groupingBy(e -> e.getCountry() + e.getGender(),
Collectors.averagingDouble(RowData::getIncome)));

TA貢獻1836條經驗 獲得超5個贊
老實說,我正在看你的第二個groupBy
,我不知道發生了什么。要立即按性別 + 國家/地區分組,我最好這樣:
final Map<Pair<String, String>, List<RowData>> collect = rowDataStream.stream() .collect(groupingBy(rowData -> Pair.of( rowData.getCells().get(0).getValue(), rowData.getCells().get(1).getValue() )));
Pair 只是任何兩個值的簡單容器,您可以使用 apache commons pair、vavr tuple 或創建您自己的。
添加回答
舉報