cafebabe1991:
私は、次のオブジェクトがあります。
class RowData
{
private List<RowCell> cells;
}
class RowCell
{
private String headerName;
private String value;
}
私は、これらのオブジェクトに次のCSVをロードしました。
Country,Gender,Income
IND,M,23531
IND,F,2331
IND,M,2311
SNG,M,22111
HYD,F,20012
私は何をする必要がありますか ?
国や性別によってグループ化された平均所得を探します。
私はこれまで何をしましたか?
List<String> criteria = Arrays.asList("Country", "Gender", "Income");
List<RowData> rowDataStream = rows.stream().map(rowData -> new RowData(getMatchingCells(criteria, rowData))).collect(Collectors.toList());
// group by country
Map<String, List<RowData>> collect = rowDataStream.stream().collect(groupingBy(rowData -> rowData.getRowCells().get(0).getValue()));
// group everything above by gender now.
Map<Map<String, List<RowData>>, List<List<RowData>>> collect1 = collect.values().stream().collect(groupingBy(rowData -> rowData.stream().collect(groupingBy(o -> o.getRowCells().get(1).getValue()))));
質問
- これはそれを行うための正しい方法ですか?
- これは、過度に複雑なようです。あなたはそれを行うには良い方法を提案することはできますか?
マイケル:
まず、あなたはおそらく意味のあるのDTO / POJOのにデータをロードする必要があります。
class Row {
String country;
String gender;
int income;
// Getters etc.
}
次に、与えられた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
とRowCell
秒):
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()))
)