>我有以下代码,我想在buildAccounts()
的List.of
中包含getNames
方法,但是当我尝试这样做时,我收到一个错误,指出所需的List<Account>
类型与提供的List <Object>
不匹配。我尝试通过添加一个返回对象而不是 List 的findAny().orElse(null)
将getNames()
的返回类型更改为Account
,但此方法不再以List
格式生成正确的输出。我的问题是,我需要进行哪些更改才能允许在不更改getNames()
输出的情况下在buildAccounts List.of
中使用getNames()
?
public List<Account> buildAccounts(MetaData metaData){
return List.of(
createAccount(metaData.getAccountName(), metaData.getaccountType()), getNames(metaData, metaData.getaccountType()));
}
public List<Account> getNames(MetaData metadata, AccountType type){
return metaData.getNames().stream()
.map(n -> createAccount(n, type))
.collect(Collectors.toList());
}
public Account createAccount(String name, AccountType accountType){
....
}
你的问题是List.of不能这样使用。如果 getNames 的输出无法更改,则需要更改 buildAccounts,而不是在此处使用 List.of。
由于您已将此问题标记为流并在其他函数中使用了流,因此一种方法是在 buildAccounts 中创建两个流并将它们组合在一起。
public List<Account> buildAccounts(MetaData metaData){
Stream firstStream =
Stream.of(createAccount(metaData.getAccountName(), metaData.getaccountType()));
Stream secondStream =
getNames(metaData, metaData.getaccountType()).stream();
return Stream.concat(firstStream, secondStream).collect(Collectors.toList());
}
在我看来,您尝试将一个Account
(由createAccount(...)
重新调整)添加到Account
(由getNames(...)
重新调整)的List
中。
但它不是那样工作的。List.of
采用任意数量的相同类型的元素并对其进行List
。
您将需要这样的东西:
public List<Account> buildAccounts(MetaData metaData){
List<Account> list = new ArrayList<>(getNames(metaData, metaData.getAccountType()));
list.add(0, createAccount(metaData.getAccountName(), metaData.getAccountType()));
return list;
}
在我看来,以下内容与您想要实现的目标相同?
public List<Account> buildAccounts(MetaData metaData){
List<Account> accounts = getNames(metaData, metaData.getAccountType());
accounts.add(createAccount(metaData.getAccountName(), metaData.getaccountType()));
return accounts;
}