简体   繁体   English

映射地图<String, List<> &gt; 带列表&lt;&gt;

[英]Mapping Map<String, List<>> with List<>

I need some help mapping a Map<String, List<Fee>> with a List<FeeRequest> .我需要一些帮助来映射Map<String, List<Fee>>List<FeeRequest>

Fee object looks like this: Fee对象如下所示:

private String feeCode;

FeeRequest objects looks like this: FeeRequest对象看起来像这样:

private String feeCode;
private String debtorAccount;

So what I need is to map:所以我需要的是映射:

String debtorAccount(from map) -> debtorAccount(from List)字符串 DebororAccount(来自地图) -> DebororAccount(来自列表)

feeCode(from List from map) -> feeCode(from List)费用代码(来自地图的列表) ->费用代码(来自列表)

I want to try not to use foreach , but instead learn to properly use .stream().map() features.我想尽量使用foreach ,而是学习正确使用.stream().map()功能。

What I've managed to do:我设法做到了:

Map<String, List<Fee>> feeAccounts is parsed from another method. Map<String, List<Fee>> feeAccounts是从另一个方法解析出来的。

 List<FeeRequest> feeRequests = feeAccounts.entrySet().stream().map(feeAcc -> {
        FeeRequest request = new FeeRequest();
        request.setDebtorAccount(feeAcc.getKey());
        request.setFeeCode(...);
        return request;
    }).collect(Collectors.toList());

I think that my approach is bad, but I don't know how to make it work.我认为我的方法很糟糕,但我不知道如何使它起作用。 I tried looking at some examples but they're too basic.我试着看一些例子,但它们太基本了。 So I would be glad to get any help.所以我很乐意得到任何帮助。 Thanks!谢谢!

If each Fee instance should generate a FeeRequest instance, you need flatMap :如果每个Fee实例都应该生成一个FeeRequest实例,则需要flatMap

List<FeeRequest> feeRequests =
    feeAccounts.entrySet()
               .stream()
               .flatMap(feeAcc -> feeAcc.getValue()
                                        .stream()
                                        .map(f -> {
                                            FeeRequest request = new FeeRequest();
                                            request.setDebtorAccount(feeAcc.getKey());
                                            request.setFeeCode(f.getCode());
                                            return request;
                                        }))
               .collect(Collectors.toList());

If FeeRequest has a constructor with two arguments you can use something like this:如果FeeRequest有一个带有两个参数的构造函数,你可以使用这样的东西:

feeAccounts.entrySet().stream()
        .flatMap(
                accountEntry -> accountEntry.getValue().stream().map(
                        fee -> new FeeRequest(
                                accountEntry.getKey(),
                                fee.getFeeCode()
                        )
                )
        ).collect(toList());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM