これはjava8でネストされたGROUPBYを使用する正しい方法は何ですか?

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()))));

質問

  1. これはそれを行うための正しい方法ですか?
  2. これは、過度に複雑なようです。あなたはそれを行うには良い方法を提案することはできますか?
マイケル:

まず、あなたはおそらく意味のあるの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)
)

そして構造のために、あなたは(のリストを与えているRowDataRowCell秒):

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()))
)

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=231741&siteId=1