分组并与嵌套列表求和 [英] grouping and sum with nested lists

查看:164
本文介绍了分组并与嵌套列表求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有嵌套的列表,并且我试图使用java流和收集器进行分组和求和以获得所需的结果.这样我就不能循环多个SubAccounts.我必须使用for循环或其他某种逻辑.我想使用流API实现.有可能吗

I have nested lists and I'm trying to group and sum to get the desired result using java streams and collectors . With this I'm not able to loop over multiple SubAccounts. Either I have to use for loop or some other logic. I want to achieve using streams api. Is there any possibility for that

Map<Long, BigDecimal> assetQuanMap = subAccounts.getAssets.parallelStream().collect(Collectors.groupingBy(Asset::getAssetId, Collectors.reducing(BigDecimal.ZERO, Asset::getQuantity, BigDecimal::add)));

我有下面的类或表示形式:

I'm having the below classes or representation :

    Account
        SubAccount1
            Assets
                1 - 20
                2 - 30
                3 - 40
        SubAccount2
            Assets
                1 - 10
                2 - 5
                3 - 3
        SubAccount3

                1 - 3
                2 - 3
                3 - 4

Accounts类如下:

Accounts class looks like :

Public class Account{
  List<SubAccounts> list;
}

Public Class SubAccounts    {
   List<Assets> list;
}

Public class Assets{
    Long assetId;
    BigDecimal quantity ;
}

我试图在Map中获得如下结果.基本上,对于每个子帐户,我都需要在类似于下面的帐户级别对资产进行分组

I'm trying to get the result as below in Map . Basically for each of the subAccounts i need to group the assets at account level which looks similar to below

1 - 33
2 - 38
3 - 47

推荐答案

您必须使用两个 代码中的

是一个字符串,因此map的键应该是一个字符串,或者您必须对其进行转换,或者在您的类中对其进行更改,就像这样:

from your code assetId is a String so the key of map should be a String, or you have to convert it, or change it in your class, like so :

Map<Long, BigDecimal> collect = accounts.stream()
        .flatMap(account -> account.getList().stream())
        .flatMap(subAccount -> subAccount.getList().stream())
        .collect(Collectors.groupingBy(asset -> Long.valueOf(asset.getAssetId()),
                Collectors.reducing(
                        BigDecimal.ZERO,
                        Assets::getQuantity,
                        BigDecimal::add
                )
        ));


注释

  • 不要在类的名称中使用复数;
  • 不要将变量命名为list,请使用另一个有效的名称;
  • 不要使用assetId作为属性名称,而只需使用id;
  • 不要在变量assetList的名称中使用List,而在最后使用s,例如assetsaccounts.
  • don't use plurals in the name of classes;
  • don't name variable as list, use another significant name;
  • don't use assetId as a name of attribute instead use just use id;
  • don't use List in the name of variables assetList, instead use s in the end for example assets or accounts.

这篇关于分组并与嵌套列表求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆