gpt4 book ai didi

java - 尝试映射列表时出现不兼容类型错误

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:59:55 26 4
gpt4 key购买 nike

我有一个要填写的 FeeAccount 列表。我想使用 .stream.map() 来完成它。我设法做的是创建一个方法来映射我的列表并将其返回。我使用在网上找到的其他一些示例编写了这段代码。我的问题是它以某种方式返回了一个与 List 不兼容的列表。

我收到一个错误:不兼容的类型。 Required List but 'map' was inferred to Stream: no instance(s) of type variable(s) R exist 因此 Stream 符合 List

据我所知,问题出在我使用 collect(Collectors.toList()) 的部分。但我不确定。我什至不清楚错误消息的含义。

也许有人可以解释我做错了什么?它与 .stream.map() 一起使用吗?因为我以前从未使用过它。或者问题出在其他地方。

Method(List<contract> contractList){
List<FeeAccount> feeAccounts = new ArrayList<>();

feeAccounts = contractList
.stream()
.map(contract -> {

List<Fee> monthlyFees=...;

return monthlyFees.stream()
.map(monthlyFee -> {
FeeAccount account = new FeeAccount();
account.setFeeCode(monthlyFee.getFeeCode());
account.setDebtorAccount(contract.getDebtorAccount());
return account;
}).collect(Collectors.toList());
});}

最佳答案

你有两个嵌套的 map操作。外部转换 contractList<FeeAccount> , 内部转换 FeeFeeAccount .

因此,您的管道会导致 Stream<List<FeeAccount>>无需终端操作。

如果你添加一个.collect(Collectors.toList())最后,你会得到一个 List<List<FeeAccount>> .

如果你想将所有这些内部列表合并成一个输出列表,你应该使用 flatMap .

获得单位List :

List<FeeAccount> feeAccounts = 
contractList.stream()
.flatMap(contract -> {
List<Fee> monthlyFees=...;
return monthlyFees.stream()
.map(monthlyFee -> {
FeeAccount account = new FeeAccount();
account.setFeeCode(monthlyFee.getFeeCode());
account.setDebtorAccount(contract.getDebtorAccount());
return account;
});
})
.collect(Collectors.toList();

关于java - 尝试映射列表时出现不兼容类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56971778/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com