ネストされたオブジェクト上のラムダとストリームの使用

R_Jain:

私は、ラムダを使用すると、複雑なネストされたオブジェクトのストリームや日付を比較したいです。私は、ラムダ式を使用してそれを行うことができますどのように缶誰かのヘルプ

オブジェクトの下から私は、所有権の開始日<社員入社日付ですべての資産のアイテムIDをフィルタリングしたいとアレイリストにすべてのこれらのIDを入れたいです

私が持っているコードは、これまでに私のすべての資産のアイテムIDを与え、私はemp.joiningDateでitem.ownership.startDateを比較するためにフィルタを使用する方法を知りません

{
  "transactionDate": "",
  "employees": [
    {
      "joiningDate": "2018-06-12T07:13:48.504Z",
      "assets": [
        {
          "assetItem": [
            {
              "id": "1",
              "ownership": {
                "startDate": "2017-06-12T07:13:48.506Z",
                "endDate": "2017-06-12T07:13:48.506Z"
              }
            }
          ]
        },
        {
          "assetItem": [
            {
              "id": "2",
              "ownership": {
                "startDate": "2018-06-12T07:13:48.506Z",
                "endDate": "2018-06-12T07:13:48.506Z"
              }
            }
          ]
        },
        {
          "assetItem": [
            {
              "id": "3",
              "ownership": {
                "startDate": "2017-06-12T07:13:48.506Z",
                "endDate": "2017-06-12T07:13:48.506Z"
              }
            }
          ]
        }
      ]
    }
  ]
}

以下は、私が変更したい私が持っているコードです。

  List<String> assetList = object.getEmployees().stream().
            flatMap(emp -> emp.getAssets().stream()).
            flatMap(asset -> asset.getAssetItem().stream()).
            map(item -> item.getId()).collect(Collectors.toList());

期待がリストにのみ、資産アイテムID 2を持つことです。

また:

混合とアプローチforのコレクションのループ反復Employeeの従業員当たりの資産上にストリーミングし、次いでfilterINGのとmap条件にそれぞれアイテムIDに基づいてピング。

List<String> assetItemIds = new ArrayList<>();
for (Employee employee : employees) {
    assetItemIds.addAll(employee.getAssets().stream()
            .flatMap(asset -> asset.getAssetItem().stream())
            .filter(assetItem -> assetItem.getOwnerShip().getStartDate() >= employee.getJoiningDate())
            .map(AssetItem::getId)
            .collect(Collectors.toList()));
}

単一ストリーム動作中にこの変換の少し複雑な構造は、エントリを作成することであろうけれどもEmployee、およびAssetItemフィルタ操作はトリックであるおよびそれに応じた値をマッピングにストリームを。これは以下のように実現することができます。

List<String> assetItemIds = employees.stream()
        .map(emp -> new AbstractMap.SimpleEntry<>(emp,
                emp.getAssets().stream()
                        .flatMap(asset -> asset.getAssetItem().stream())
                        .filter(assetItem -> assetItem.getOwnerShip().getStartDate() >= emp.getJoiningDate())))
        .flatMap(e -> e.getValue().map(AssetItem::getId))
        .collect(Collectors.toList());

おすすめ

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